2014-01-07 74 views
0

在官方Qt文档:的QThread和GUI线程澄清

如前所述,每个程序都有一个线程在启动时。这个线程被称为“主线程”(在Qt应用程序中也称为“GUI线程”)。 Qt GUI必须在这个线程中运行。所有部件和几个相关的课程,比如,QPixmap,不要在辅助线程工作现在

,在Qt的项目,我已经试过下面的代码:

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

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

凡DetectList是一类由QWidget派生。代码为什么编译和运行? DetectList不必只在主线程中运行?

+0

DetectList是否显示任何GUI元素,还是只是调用过程? – TheDarkKnight

+1

“代码为什么编译和运行?” - >你的意思是你甚至没有得到运行时警告?你可以向我们展示这些代码吗? – lpapp

回答

2

像拉斯洛·帕普指出您收到一个战国和moveToThread没有任何效果。战争会说:
QObject::moveToThread: Widgets cannot be moved to a new thread

请参阅source code of moveToThread

我建议你描述你在做什么,以及为什么你需要做的事情。我很确定有更好的解决方案(如Qt Concurrent)。

1

该程序将编译和运行,因为从C++起诉它是语法上正确的。

什么Qt文档说的是,在与主线程不同的线程中运行与GUI相关的代码是不正确的,如果发生这种情况,那么应用程序可能会在运行时崩溃。

在你前面的示例代码,如果DetectList是对象是一些GUI元素交互那么你的程序将崩溃:

// If the process implementation interacts with GUI elements then the application will crash 
void DetectList::process() 
{ 
    // a simple gui interaction 
    checkBox->setChecked(true); 
}