Search code examples
c++multithreadingqtuser-interfaceqapplication

How to use threads to instantiating multiple QApplication


I found a solution to prevent app.exec() from blocking the main thread here.

I tried to implement this but I got the following errors:

WARNING: QApplication was not created in the main() thread.
QWidget: Cannot create a QWidget without QApplication

Here is my code:

PB is a class that has a static function which initializes the GUI.

pb.cpp:

bool PB::Init(int argc, char *argv[],
        int ID) {

    QApplication app(argc, argv);
    PB PB(ID); // The constructor creates an instance of the pushbutton qt object
    app.exec();
    return true; // Do I even need this because app.exec() runs an infinite loop right?

}

main.cpp:

int main(int argc, char *argv[]) {

    std::thread first(&PB::Init, argc, argv, 0);
    std::thread second(&PB::Init, argc, argv, 1);

    first.join();
    second.join();

}

The thing is, I am initializing QApplication in the classes so it should work... I made sure that it would work with a seperate test where QApplication is not used in the main:

int main(int argc, char *argv[]) {

    PB::Init(argc, argv, 0);

}

This code works fine. So it is only when I add the thread in that I get this error.


Solution

  • You can create QApplication in different thread, but you should create all GUI classe's objects in this thread otherwise you get undefined behavior. QApplication is singleton, so you can't create multiple instances of QApplication in different threads.