C++ Qt忙处理对话框

C++ Qt忙处理对话框,c++,qt,C++,Qt,我有一个应用程序,运行一个算法需要花费很多时间。当过滤器运行时,GUI显然会阻塞,直到算法完成 因此,我希望在算法运行时显示一个模式对话框,显示一条“忙碌”消息。这样,GUI仍然能够响应。我试着这样做: dialog->setModal(true); dialog->show(); // Run the code that takes up a lot of time .... dialog->close(); 然而,这样会显示对话框,但它是全黑的(未绘制),我能解决这个

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

因此,我希望在算法运行时显示一个模式对话框,显示一条“忙碌”消息。这样,GUI仍然能够响应。我试着这样做:

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

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

dialog->close();

然而,这样会显示对话框,但它是全黑的(未绘制),我能解决这个问题吗?

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

您可以使用
QFuture
QtConcurrent::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
    }

};
TAlgoResult HeavyAlgorithm(){/*这里是算法例程*/};
QFuture RunHeavyAlgorithmAsync()
{
QtConcurrent::run([&](){return HeavyAlgorithm();});
}
//类,该类调用algo
类AlgoCaller
{
未来观察者未来观察者;
QDialog*mp\u model\u对话框;
AlgoCaller()
{
QObject::connect(&m_future_watcher,&QFutureWatcher::已完成,
[&]()
{
mp_modal_dialog->close();//计算完成后关闭对话框
})
}
void CallAlgo()//从主线程调用
{
mp_modal_dialog->show();//在算法启动前显示对话框
m_future_watcher.setFuture(RunHeavyAlgorithmAsync());
//在后台启动algo
//主线程未被阻止,可以处理事件
}
};

注释中的代码很可能阻止了事件循环处理。将其移动到另一个执行线程。是否可以提供一个示例?@manatttta提供。如果您能找到它,请看一看。小心,
close
方法不是线程安全的,您不能从另一个线程调用它!