按下按钮后如何停止后台循环

How to stop background loop after pushing button?

本文关键字:何停止 后台 循环 按钮      更新时间:2023-10-16

在我的程序中,我打开一个窗口并运行一个大循环。在QTextEdit显示进度。我添加了一个取消按钮来停止大循环。

因此,在窗口构造函数中,我运行一个如下所示的方法,

void start()
{
    for (size_t i=0, i<10000000; ++i)
    {
        // do some computing
        QApplication::processEvents(); // Else clicking the stop button has no effect until the end of the loop
        if (m_stop) break; // member m_stop set to false at start.
    }
}

因此,当我单击停止按钮时,它会运行插槽

void stopLoop()
{
    m_stop = true;
}

该方法的问题在于processEvents()执行时间减慢了太多。但也许这是不可避免的.

我想尝试使用信号和插槽,但我似乎想不出如何将按下的停止按钮与循环连接起来。

或者,信号和插槽与否,也许有人有更好的方法来实现这一目标?

编辑

按照此线程建议,我现在有一个工作线程/线程方案。所以我在一个窗口构造函数中

Worker *worker;
QThread *thread ;
worker->moveToThread(thread); 
connect(thread, SIGNAL(started()), worker, SLOT(work()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start(); 

这似乎工作正常。但是我现在如何引入QTimer

我应该将QTimer连接到线程的start()函数

connect(timer, &QTimer::timeout, thread, &QThread::start);

或者,我应该将线程连接到QTimerstart()函数吗?

connect(thread, SIGNAL(started()), timer, &QTimer::start());

或者两者都不是...但是,如何呢?

使用 QTimer

void start()
{
    this->timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MyObject::work);
    connect(stopbutton, &QButton::clicked, timer, &QTimer::stop);
    connect(stopbutton, &QButton::clicked, timer, &QTimer::deleteLater);
    connect(this, &MyObject::stopTimer, timer, &QTimer::deleteLater);
    connect(this, &MyObject::stopTimer, timer, &QTimer::stop);
    timer->setInterval(0);
    timer->setSingleShot(false);
    timer->start();
}
void work()
{
   //do some work and return
   if (done)emit stopTimer();
}

为了不那么"块状",您可以做的一件事是使用 QThread 在工作线程中完成工作。然后,减速将不再是一个大问题,而您仍然可以优雅地终止工作。

我也会重新考虑这个大数字迭代以支持QTimer.然后,基本上取消按钮或计时器的超时将触发工作线程循环中断。在这种情况下,迭代的 while 条件将是m_stop守卫。