chacham15 chacham15 - 2 months ago 12
C++ Question

How do I create a Window in different QT threads?

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

in the
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.


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:

  • 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
      virtual bool event( QEvent *ev )
        if( ev->type() == QEvent::User )
          w = new QWidget;
          return true;
        return false;
  • create QApplication object in main thread

  • another thread body:

      // 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, :)