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

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

问题描述

我的程序的主(函数 main 在那里)线程是为非 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 和移动所有代码的工作,你可能会发现 QtConcurrent::run 函数很有用 - 它允许您异步运行函数.

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天全站免登陆