1

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.

Community
  • 1
  • 1
jlcv
  • 1,688
  • 5
  • 21
  • 50
  • 2
    Why do you think you need two QApplications? QEventLoop or QThread::exec() would provide event loop if that what's you need. – Vincas Dargis Apr 24 '15 at 10:39
  • Don't I need QApplication just to be able to construct a QWidget? When I remove the QApplications I get `QWidget: Must construct a QApplication before a QWidget` error. – jlcv Apr 24 '15 at 12:07
  • Sorry, but Qt widgets does not support multitheading. QWidget must be created on single (main) thread where QApplication resides. Use threads to calculate data, and pass results using Qt::QueuedConnection signals to the main thread to be visualized on GUI. Check [threaded mandelbrot example](http://doc.qt.io/qt-5/qtcore-threads-mandelbrot-example.html) about main (GUI) and worker thread communication. – Vincas Dargis Apr 24 '15 at 12:29

1 Answers1

5

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.

gomons
  • 1,946
  • 14
  • 25
  • One point: there are no such thing as "main thread". You can safely create `QApplication` in "non-main" thead and there will be no UB. But you right, that `QApplication` is singleton. @Justin has problem when he creates second instance of `QApplication`. It doesn't depends on threads. Please, fix you answer. – Dmitry Sazonov Apr 24 '15 at 11:28