10

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);
}
cbuchart
  • 10,847
  • 9
  • 53
  • 93
neda
  • 329
  • 1
  • 4
  • 15
  • You would need to display or save the image again after adding the text, or restructure your code to draw the text then save the image. Right now you save it before anything is changed. – Retired Ninja Jul 02 '16 at 05:08
  • I edit code, but it was useless. – neda Jul 02 '16 at 05:35
  • Pay careful attention to which image you are passing to the painter and which you are saving. They do not match. – Retired Ninja Jul 02 '16 at 05:37

1 Answers1

9

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.

cbuchart
  • 10,847
  • 9
  • 53
  • 93
  • 2
    Note: To optimize the rendering (e.g. while in paintEvent of a QWidget), prefer **QStaticText** over using p.drawText. For one-time usage, however, this solution is equivalent. – Adrian Maire Sep 20 '21 at 10:54