在我的程序中,我打开一个窗口并运行一个大循环。我在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();
这似乎工作正常。但是我怎么能介绍 a QTimer
now 呢?
我应该连接QTimer
到线程的start()
函数吗
connect(timer, &QTimer::timeout, thread, &QThread::start);
或者,我应该将线程连接到QTimer
'sstart()
函数吗?
connect(thread, SIGNAL(started()), timer, &QTimer::start());
或者两者都不是......但是,如何?