-1

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.

joaopedro
  • 75
  • 9

2 Answers2

2

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++.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36
  • That is the timer to run the function I think, probaly inside of SLOT() Is the name of the function? – joaopedro Dec 02 '20 at 15:41
  • I finally understand your code, but it took me a while because Im beginner on Qt and C++. I answered my own question with a best approach to beginner users! – joaopedro Dec 03 '20 at 13:00
  • 1
    @JoãoPedro You're jumping into the deep end trying to learn C++ and Qt at the same time. – Joseph Larson Dec 03 '20 at 17:26
0

To do the loop, I use QTimer, which run the slot pressButton multiple times until stop(); function of QTimer is executed. Of course, to use this method I have to recode the program, to improve the algorithm.

QTimer loop:

void MainPrograma::on_pushTurnOn_clicked()
{
    tierLoop = new QTimer(this);
    timerLoop->setInterval(5000);
    timerLoop->setSingleShot(true);
    connect(timerLoop, SIGNAL(timeout()), SLOT(on_pushTurnOn_clicked()));
    
    QPushButton *ThirdButton = uimain->QPushButton_3;
    Nmb2 = 2
    Nmb4 = 4;

    if(Busy==1){
        ThirdButton->setEnabled(false);
    }
    if(Busy==0){

        timerLoop->start(); //start the loop

        StartFunction(Nmb2, Nmb4);
        if(X==1){
            ThirdButton->setEnabled(false);     
        }
        if(X==0){
            ThirdButton->setEnabled(true);
        }
    }
}

void MainPrograma::on_pushTurnOff_clicked()
{
    timerLoop->stop(); //stop the loop
}

QTimer declaration on .h:

private:
    QTimer *timerLoop;

I still do not understand how to use QThread... But the loop is already answered!

joaopedro
  • 75
  • 9