如何在 QThread 上启动循环

How to start a loop on a QThread

如何通过按 QPushButton 在不同的线程上开始循环?

主要思想是,当点击pushButtonStart时,在QThread上开始一个循环,当点击pushButtonStop时,在 QThread.

中停止 loop

循环可以通过QTimerfor循环或while循环来完成,但他需要一种通过按下按钮来停止的方法。

我有这段代码可以创建一个新的计时器并在它触发时建立连接。这是在开始代码中。

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

我的“停止 运行”按钮将 programCreated 设置为 false,checkTimerFired 以此开头:

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

这应该是您需要的特定于 Qt 的东西。剩下的就是简单的C++。

为了执行循环,我使用 QTimer,运行 插槽 pressButton 多次,直到执行 QTimerstop(); 函数。当然,要使用这种方法,我必须重新编写程序,改进算法。

QTimer 循环:

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 关于 .h 的声明:

private:
    QTimer *timerLoop;

还是不懂怎么用QThread...但是循环已经回答了!