QThread 和 GUI 线程说明 [英] QThread and GUI Thread clarification

查看:92
本文介绍了QThread 和 GUI 线程说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在官方 Qt 文档中:

In the official Qt Documentation:

如前所述,每个程序在启动时都有一个线程.该线程称为主线程"(在 Qt 应用程序中也称为GUI 线程").Qt GUI 必须在这个线程中运行.所有小部件和几个相关的类,例如 QPixmap,在辅助线程中不起作用

As mentioned, each program has one thread when it is started. This thread is called the "main thread" (also known as the "GUI thread" in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example QPixmap, don't work in secondary thread

现在,在一个 qt 项目中,我尝试了以下代码:

Now, in a qt project i've tried the following code:

QThread* thread = new QThread;
DetectList *list = new DetectList;
list->moveToThread(thread);

connect(thread, SIGNAL(started()), list, SLOT(process()));
thread->start();

其中 DetectList 是 QWidget 派生的类.为什么代码编译并运行?DetectList 不是必须只在主线程中运行吗?

Where DetectList is a class derived by QWidget. Why the code compile and run? DetectList doesn't must be run only in the main thread?

推荐答案

就像 Laszlo Papp 指出的那样,您收到了一场战争,而 moveToThread 没有效果.战将说:
QObject::moveToThread:小部件不能移动到新线程

Like Laszlo Papp point out you are receiving a warring and moveToThread have no effect. Warring will say:
QObject::moveToThread: Widgets cannot be moved to a new thread

参见 .

See source code of moveToThread.

我建议您描述一下您到底想做什么以及为什么需要线程.我很确定有更好的解决方案(比如 Qt Concurrent).

I recommend you to describe what are you exacly trying to do and why you nead threads. I'm pretty sure there is better solution (like Qt Concurrent).

这篇关于QThread 和 GUI 线程说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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