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);
}
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.