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:

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?
                        
Ok this nice bug.
You are using uninitialized
QImage!http://doc.qt.io/qt-4.8/qimage.html#QImage-2
So in each iteration same piece of memory is is assigned to
QImage, which previously was owned by previousQImage. You were unlucky and in first iteration you have clear piece of memory instead some garbage values.Call fill method to fix this.