gpt4 book ai didi

c++ - 按下按钮后如何停止背景循环?

转载 作者:搜寻专家 更新时间:2023-10-31 01:44:54 25 4
gpt4 key购买 nike

在我的程序中,我打开一个窗口并运行一个大循环。我在 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();
}

关于c++ - 按下按钮后如何停止背景循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22917275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com