Search code examples
c++loopsqtqthreadqtimer

How to start a loop on a QThread


How can I start a loop on a different thread by pressing a QPushButton?

The main idea is, when pushButtonStart is clicked, start a loop on a QThread, and when pushButtonStop is clicked, stops the loop in the QThread.

The loop can be done by QTimer, for loop or while loop, but he needs a way to stop by pressing a button.


Solution

  • I have this code to create a new timer and set up a connection when it fires. This is in the Start code.

    checkTimer = new QTimer(this);
    connect( checkTimer, SIGNAL(timeout()), this, SLOT(checkTimerFired()) );
    checkTimer->start(3000);
    

    My "stop running" button sets programCreated to false, and checkTimerFired starts with this:

    if (!programCreated) {
        checkTimer->stop();
        return;
    }
    

    That should be the Qt-specific things you need. The rest is simple C++.