Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw text on image using Qt

I want to draw text on an image. I use this code, but I do not see any text on the image.

void ImageSaver::save(const QString &path) const {       
   QImage image(img_);
   QPainter p(&image);
   p.setPen(QPen(Qt::red));
   p.setFont(QFont("Times", 12, QFont::Bold));
   p.drawText(image.rect(), Qt::AlignCenter, "Text");
   image.save(path);
}
like image 620
neda Avatar asked Jul 02 '16 04:07

neda


1 Answers

QPainter must finish the I/O operations before the image is valid. You can either do it after QPainter object destruction or use the begin/end methods.

bool ImageSaver::save(const QString &path) const {    
  QImage image(img_);
  QPainter p;
  if (!p.begin(&image)) return false;

  p.setPen(QPen(Qt::red));
  p.setFont(QFont("Times", 12, QFont::Bold));
  p.drawText(image.rect(), Qt::AlignCenter, "Text");
  p.end();

  return image.save(path);
}

P.S.: I've added the bool return for better error tracking.

like image 182
cbuchart Avatar answered Oct 13 '22 16:10

cbuchart