QT: QGraphicsView not updating from inside loop

A. Kriegman :

I'm trying to draw a picture to the screen repeatedly from inside an infinite loop. When I try to draw the picture to the QGraphicsView, it doesn't update unless I break from the loop. Here is my function with the infinite loop:

void MainWindow::displayNoise() {
    QImage noise(WIDTH, HEIGHT, QImage::Format_RGB32);
    float t = 0;

    while (true) {
        // Populate noise

        rendered_image = noise;
        DisplayQImage(rendered_image);
        t += 0.200;
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }
}

And here is DisplayQImage():

void MainWindow::DisplayQImage(QImage &i)
{
    QPixmap pixmap(QPixmap::fromImage(i));
    graphics_scene.addPixmap(pixmap);
    graphics_scene.setSceneRect(pixmap.rect());
    ui->scene_display->setScene(&graphics_scene);
}

Note that graphics_scene and rendered_image are members of MainWindow. If I insert a break statement after my call to DisplayQImage then the first frame renders, but if I don't exit the displayNoise function then the widget doesn't update. I set up a signal so that when I press N it calls displayNoise, and I know the loop is looping. Why isn't the picture showing?

David van rijn :

It is because you are not giving the eventloop time to do it's thing. Your function is being called from the eventloop, and the rendering is called from the same eventloop, because they live in the same thread. So you have two options:

I think the first option is probably the nicest way.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=375941&siteId=1