Question

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 ?

Was it helpful?

Solution 2

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);
    }        
}

OTHER TIPS

GUI will not update itself until gui thread is free of other tasks. However, you can force it using

qApp->processEvents();

Following is example of very bad coding style, but that might be what you want.

#include "mainwindow.h"
#include <QApplication>
#include <thread>

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

    qint8 k = 15;

    using namespace Qt;

    QPalette pal;
    QColor col = red;

    while (k--)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
        pal.setBrush(w.backgroundRole(), QBrush(col));
        w.setPalette(pal);
        col = col == red ? blue : red;

        qApp->processEvents();
    }
    return a.exec();
}

To run this, you will have to add QMAKE_CXXFLAGS += -std=c++11 to your '.pro' file. And if you want to understand things better, i recommend to read about qt events.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top