Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using QPainter with QCoreApplication

Tags:

c++

qt

We have an application (QCoreApplication) that takes some images as input, does something to them, and exports them again. We now need to add some text to the images, and tried to do this with the QPainter class. It all worked well when using it in one of our other apps (using QApplication), but not in our main QCoreApplication app.

Here is the code:

void drawTextOnImage(QImage* image, const QString& text, const QFont& font)
{
    QPainter p;
    if (!p.begin(image)) return;

    p.setFont(font);
    p.drawText(image->rect(), Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, text);

    p.end();
}

The application crashes on the drawText line.

Any ideas?

It is a very simple text, so suggestions without using Qt will also be appreaciated.

like image 426
OleG Avatar asked Oct 23 '25 08:10

OleG


2 Answers

When using classes from "Qt Gui" like QPainter, you are supposed to use a QGuiApplication, not a QCoreApplication.

You might get lucky and be able to make some GUI stuff works while using only a QCoreApplication. But as you have discovered, it makes your application very brittle. Some classes like QPixmap will print an error message, but others will just crash.

The same is applicable with "Qt Widget": if you use a widget related class, you must use a QApplication.

Note that since QApplication inherits QGuiApplication, if you have a QApplication you can use "Qt Gui".

like image 70
Benjamin T Avatar answered Oct 24 '25 21:10

Benjamin T


In case you need to run a non-GUI application on something without a windowing system, you need, aside from creating an instance of QGuiApplication, to also choose an appropriate Qt platform.

For me, offscreen platform worked fine. I was generating images with textual elements and saving them to files on a headless Raspberry Pi. My code then was like the example below. Note that setenv is a POSIX function and may need a replacement on Windows, though I'm not sure whether windowless Windows is a thing at all.

#include <stdlib.h>
#include <QImage>
#include <QPainter>
#include <QGuiApplication>

int main(int argc, char** argv)
{
    setenv("QT_QPA_PLATFORM","offscreen",1);
    QGuiApplication app(argc,argv);

    QImage img(128,128, QImage::Format_RGB888);
    img.fill(Qt::white);
    QPainter p(&img);
    p.drawText(QPoint(0,64), "Works!");
    img.save("/tmp/test.png");
}
like image 34
Ruslan Avatar answered Oct 24 '25 21:10

Ruslan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!