qtloopsmainwindow

How to update the QT Mainwindow at each loop in mainwindow.cpp


My main.cpp look like this:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

An in my mainwindow.cpp I want to show a different image at each loop in "while", so it would look like this:

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    image = load_an_image
    int i=0;
    while (i<15)
    {
        show image in the MainWindow
        waitkey (wait until I press a key or wait some time)
        do something to this image for the next loop
        i++
    }
}

However the Mainwindow does not show up until the "while" is finished and I cannot find how to show the MainWindow at each loop.

Can anyone give me any advice ?


Solution

  • You could delay handling the image by using a Qtimer. Something like this: -

    MainWindow::MainWindow(QWidget *parent) :
            QMainWindow(parent),
            ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        QTimer::singleShot(5, this, SLOT(timeout());
    }
    
    // create as a slot in the MainWindow derived class
    void MainWindow::timeout()
    {
        image = load_an_image();
        int i=0;
        while (i<15)
        {
            // show image in the MainWindow
            // waitkey (wait until I press a key or wait some time)
            // do something to this image for the next loop
            i++
        } 
    }
    

    However, it would be better handled by loading the first image and then reacting to key events, rather than waiting directly in the main thread...

    void MainWindow::keyReleaseEvent(QKeyEvent* keyEvent)
    {
        if(keyEvent->key() == Qt::Key_Space) // use the space bar, for example
        {
            if(m_imageFrame < 15)
            {
                 // update the image
            }
        }
        else
        {
            QMainWindow::keyReleaseEvent(keyEvent);
        }        
    }