c++ - Qt 忙处理对话框

标签 c++ qt

我有一个应用程序,它运行一个算法需要花费大量时间。当过滤器运行时,GUI 显然会阻塞,直到算法完成。

出于这个原因,我想在算法运行时显示一个模态对话框,显示一条“忙碌”消息。这样,GUI 仍然可以响应。我尝试按如下方式进行:

dialog->setModal(true);
dialog->show();

// Run the code that takes up a lot of time
....

dialog->close();

但是,这样显示出来的dialog却是全黑的(没有画出来),哎,请问这个问题能解决吗?

最佳答案

如果 GUI 必须响应,重型算法应该在非主(非 GUI)线程中运行。 为了响应,GUI 必须能够访问主线程以在事件循环中处理事件。

您可以使用 QFutureQtConcurrent::run 来实现它。

QFuture 用法示例:

TAlgoResult HeavyAlgorithm() {/* Here is algorithm routine */};
QFuture<TAlgoResult> RunHeavyAlgorithmAsync() 
{
    QtConcurrent::run([&](){return HeavyAlgorithm();});
}

// class which calls algo
class AlgoCaller
{
    QFutureWatcher<TAlgoResult> m_future_watcher;
    QDialog*                    mp_modal_dialog;

    AlgoCaller()
    {
        QObject::connect(&m_future_watcher, &QFutureWatcher<void>::finished, 
        [&]()
        {
            mp_modal_dialog->close(); // close dialog when calculation finished
        })
    }

    void CallAlgo() // to be called from main thread
    {
        mp_modal_dialog->show(); // show dialog before algo start
        m_future_watcher.setFuture(RunHeavyAlgorithmAsync()); 
            // start algo in background

        // main thread is not blocked and events can be processed
    }

};

关于c++ - Qt 忙处理对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45141545/

相关文章:

c++ - Boost shared_ptr 似乎不支持运算符 ==

c++ - 在 Qtcp readyRead() 中读取可变长度消息

c++ - 每当我更改 QTableWidget.item(row, col) 时发生访问冲突

c++ - Vtable 和 *_vptr 创建时间

c++ - 在 STL 列表中存储的每个项目中存储对容器对象的引用的最有效方法

c++ - 如果在构造函数中引发异常会发生什么

qt - Material 主题似乎在 QML 中不起作用

c++ - Qt : Is it possible to add a QVBoxLayout to a QTableView

c++ - 您如何使用运算符 | 创建与现有 View 交互的自己的 View ?

c++ - LAPACK 矩阵乘法与 C++