問(wèn)題描述
我有一個(gè)應(yīng)用程序,其中每個(gè)線程(主線程除外)都需要?jiǎng)?chuàng)建自己的窗口.我嘗試創(chuàng)建一個(gè)線程,然后在 run
函數(shù)中調(diào)用 this->exec()
.但是,我什至在調(diào)用之前收到一個(gè)錯(cuò)誤: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."
我想彈出一個(gè)消息窗口.問(wèn)題是源有多個(gè)線程,每個(gè)線程可能需要彈出自己的消息.
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.
推薦答案
如果你需要在不同的(非主)線程中創(chuàng)建 QWidget(或其他一些 gui 組件),你可以在這樣的線程中實(shí)現(xiàn)它方式:
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:
創(chuàng)建包含 gui 組件的簡(jiǎn)單包裝器:
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;
}
};
在主線程中創(chuàng)建QApplication對(duì)象
create QApplication object in main thread
另一個(gè)線程主體:
..
// 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 ) );
..
開(kāi)心點(diǎn),:)
be happy, :)
這篇關(guān)于如何在不同的 QT 線程中創(chuàng)建窗口?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!