主线程繁忙时如何使Qt工作? [英] How to make Qt work when main thread is busy?

查看:148
本文介绍了主线程繁忙时如何使Qt工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我程序的主线程(有主函数)保留给非GUI任务.它调用了许多冗长的计算函数.所有已实现的GUI都在单独的线程中进行工作.

Main (function main is there) thread of my program is reserved for non-GUI tasks. It calls a number of lengthy calculation functions. All implemented GUI's have been doing their work in a separate threads.

我现在将使用Qt实现一个GUI. Qt文档说,所有与GUI相关的任务都应在主线程中完成. 就我而言,由于主线程之间的巨大延迟,因此偶尔在主线程中插入QCoreApplication :: processEvents()调用实际上是没有用的.

I'm now going to implement one more GUI using Qt. Qt documentation says all GUI related tasks should be done in main thread. In my case, inserting occasional QCoreApplication::processEvents() calls in main thread would be virtually useless due to great delays between them.

有什么方法可以克服Qt的这种限制吗? 在Qt程序的主线程中做与GUI不相关的事情是不可能的吗?

Is there any way to overcome this constraint of Qt? Is it impossible to do something non-GUI related in main thread of Qt program?

推荐答案

否,您应该在单独的线程中进行计算.正如您已经提到的,QCoreApplication::processEvents()中提供了一种变通方法,但听起来您无法为您解决该问题.

No, you should be doing your calculations in a separate thread. As you already mentioned, there is a work-around available in QCoreApplication::processEvents(), but it sounds like you're unable to make that work for you.

如果您不想完成设置QThread和移动所有代码的所有工作,则可能会发现

If you don't want to have to do all the work of setting up a QThread and moving all your code, you may find that the QtConcurrent::run function is useful - it allows you to run a function asynchronously.

一些指针:您应尝试使主(GUI)线程尽可能轻.大量的IO或计算应使用QtConcurrent :: run异步完成,或在单独的QThread中运行.根据代码的复杂程度,您也许可以摆脱QtConcurrent方法.

A few pointers: You should try and keep your main (GUI) thread as light as possible. Large amounts of IO or calculations should either be done asynchronously using QtConcurrent::run, or run inside a separate QThread. Depending on the complexity of your code, you may be able to get away with the QtConcurrent method.

这篇关于主线程繁忙时如何使Qt工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆