【发布时间】:2017-07-17 20:53:05
【问题描述】:
我正在编写一个 C++ QT5 Widget 桌面应用程序,当按下开始/停止按钮时,我需要在单独的线程上运行耗时的操作 MainWindow::performLengthyOperation(bool)。
这个耗时的操作在我的 MainWindow.h/cpp 中是一个相当冗长的方法。停止后台 IO 活动的操作大约需要 6 秒,启动大约需要 2 秒。在按下开始/停止按钮期间,UI 没有响应。本质上,在附加到我的按钮单击事件的插槽中,我需要执行以下逻辑。
void
MainWindow::on_pushButtonStart_clicked(bool checked)
{
// temporarily disable the pushbutton
// until the lengthy operation completes
mUI->pushButtonStart->setEnabled(false);
if (checked) {
// Start the timer tick callback
mTickTimer.start(APP_TICK, this);
mUI->pushButtonStart->setText("starting...");
// This method needs to somehow run in its own QT thread
// and when finished, call a slot in this MainWindow to
// re-enable the pushButtonStart and change the statusBar
// to indicate "runing..."
performLengthyOperation(true);
//mUI->pushButtonStart->setText("Stop")
//mUI->statusBar->setStyleSheet("color: blue");
//mUI->statusBar->showMessage("runing...");
} else { // Stop the protocol threads
// Stop the subsystem protocol tick timer
mTickTimer.stop();
mUI->pushButtonStart->setText("stopping...");
// This method needs to somehow run in its own QT thread
// and when finished, call a slot in this MainWindow to
// re-enable the pushButtonStart and change the statusBar
// to indicate "ready..."
performLengthyOperation(false);
// finally toggle the UI controls
//mUI->pushButtonStart->setText("Start")
//mUI->statusBar->setStyleSheet("color: blue");
//mUI->statusBar->showMessage("ready...");
}
}
当我在寻找有关如何执行此操作的示例时,我遇到了 following article,但我无法使其适应我的场景,因为我需要以某种方式将 MainWindow 放入 worker 中,以便它可以访问其 UI 小部件等这似乎有点矫枉过正。
理想情况下,我正在寻找一种简单的方法来异步运行 lambda 函数,我可以在其中放置这些耗时的操作(作为参数传入主窗口)。这比使用 QThreads 和将对象移动到线程等更可取。但是我对 QT 框架的了解还不够,无法知道这是否安全或可行。
【问题讨论】:
-
即使您传入您的窗口,也无法从其他线程对其进行操作。您需要将这些操作编组回主线程(尽管我认为 Qt 可以通过信号/插槽做到这一点)。