我有一个应用程序,其中每个线程(主线程除外)都需要创建自己的窗口。我尝试创建一个线程然后调用this->exec()
in the run
功能。然而,在我接到那个电话之前我就收到了一个错误:ASSERT failure in QWidget: "Widgets must be created in the GUI thread."
我想弹出一个消息窗口。问题在于源有多个线程,每个线程可能需要弹出自己的消息。
如果您需要在不同(非主)线程中创建 QWidget(或其他一些 gui 组件),您可以通过以下方式实现它:
-
创建包含 gui 组件的简单包装器:
// gui component holder which will be moved to main thread
class gui_launcher : public QObject
{
QWidget *w;
// other components
//..
public:
virtual bool event( QEvent *ev )
{
if( ev->type() == QEvent::User )
{
w = new QWidget;
w->show();
return true;
}
return false;
}
};
在主线程中创建QApplication对象
-
另一个线程体:
..
// create holder
gui_launcher gl;
// move it to main thread
gl.moveToThread( QApplication::instance()->thread() );
// send it event which will be posted from main thread
QCoreApplication::postEvent( &gl, new QEvent( QEvent::User ) );
..
要开心, :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)