Using QPainter with QImage in a loop not in a main thread

666 views Asked by At

With this simple loop:

for(int i=0;i<levels;i++)
{
    QImage stub(QSize(w,h),QImage::Format_RGB888);

    QPainter painter(&stub);
    painter.setFont(QFont("Monospace",8));
    painter.setPen(Qt::magenta);
    painter.drawText(stub.rect(),
                     Qt::AlignVCenter|Qt::AlignCenter,
                     QString("LAYER-%1").arg(i));

    stub.save(QString("layer%1.jpg").arg(i),"JPG");
}

I get a funny result:

layer0 layer1 layer3

Note the layer number printed on the image. This looks like some buffering problem. I should also mention that this loop runs not in the main thread. How to synchronize QPaitner and QImage saving?

1

There are 1 answers

0
Marek R On BEST ANSWER

Ok this nice bug.

You are using uninitialized QImage!

http://doc.qt.io/qt-4.8/qimage.html#QImage-2

Warning: This will create a QImage with uninitialized data. Call fill() to fill the image with an appropriate pixel value before drawing onto it with QPainter.

So in each iteration same piece of memory is is assigned to QImage, which previously was owned by previous QImage. You were unlucky and in first iteration you have clear piece of memory instead some garbage values.

Call fill method to fix this.