問題描述
我有一個應用程序,其中每個線程(主線程除外)都需要創建自己的窗口.我嘗試創建一個線程,然后在 run
函數中調用 this->exec()
.但是,我什至在調用之前收到一個錯誤:ASSERT 在 QWidget 中失敗:Widgets must be created in the GUI thread."
I have an application in which each thread (except the main thread) needs to create its own window. I tried creating a thread and then calling this->exec()
in the run
function. However, I get an error before I even get to that call: ASSERT failure in QWidget: "Widgets must be created in the GUI thread."
我想彈出一個消息窗口.問題是源有多個線程,每個線程可能需要彈出自己的消息.
I want to popup a message window. The problem is that the source has multiple threads each of which may need to popup its own message.
推薦答案
如果你需要在不同的(非主)線程中創建 QWidget(或其他一些 gui 組件),你可以在這樣的線程中實現它方式:
If you need to create QWidget(or some other gui component(s)) in different(non-main) thread(s) you can implement it in such way:
創建包含 gui 組件的簡單包裝器:
Create simple wrapper which holds gui component:
// 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 QApplication object in main thread
另一個線程主體:
..
// 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 ) );
..
開心點,:)
be happy, :)
這篇關于如何在不同的 QT 線程中創建窗口?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!