Reputation: 11
I need help in writing my static text to image file without using "QApplication app(argc, argv);" in main(). My version of QT is 5.12.2.
Currently I'm able to do this with the below code:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QCoreApplication::addLibraryPath("./plugins");
QString imagePath(QStringLiteral("./images/output/testOutput1.png"));
QImage image(500, 400, QImage::Format_RGB888);
image.fill(Qt::red);
QPainter painter;
if (!painter.begin(&image))
return;
painter.setPen(QPen(Qt::black));
painter.setFont(QFont("Times", 12, QFont::Bold));
painter.drawText(image.rect(), Qt::AlignCenter, "writing text on image");
painter.end();
image.save(imagePath);
return 0;
}
I'm trying to get a similar type solution which does not uses "QApplication app(argc, argv);" in my code.
Currently if I remove the deceleration of "QApplication app(argc, argv);" my code crashes at "painter.drawText(...);".
Upvotes: 0
Views: 560
Reputation: 126777
The most you can do is to exchange the QApplication
for a QGuiApplication
(thus avoiding the useless dependency from the QtWidgets module).
Qt initializes most of its static/global stuff inside the bowels of QCoreApplication
(for QtCore stuff)/QGuiApplication
(for QtGui stuff)/QApplication
(for QtWidgets stuff); each derives from the other, so if you have a QApplication
you already have all the stuff from Gui and Core.
The font engine (and other paint-related stuff) is initialized inside the QGuiApplication
constructor, as hinted in QFont
documentation
Note that a
QGuiApplication
instance must exist before aQFont
can be used.
so you are not going to paint without instantiating it (or a class derived from it).
Upvotes: 1