How to avoid Qt app.exec() blocking main thread

前端 未结 2 437
情深已故
情深已故 2020-11-29 05:58

I\'m new to Qt, but need to solve a difficult problem.

I\'ve created a VERY simple GUI that I need to add to an existing C++ application. The problem is, I\'m writin

相关标签:
2条回答
  • 2020-11-29 06:36

    Most of the time, "main thread" == "GUI thread", so people use those terms interchangeably -- even the official documentation does that. I agree that it's confusing though, because they don't have to be the same.^ The actual rule is this:

    GUI classes must only be accessed from the thread which instantiates QApplication/QGuiApplication

    With a plugin like yours, here is what you need to do:

    1. Create a new std::thread (NOT a QThread)
    2. Run an init function in that thread. Let it instantiate your QApplication/QGuiApplication and start the event loop
    3. Ensure that all your GUI objects are accessed from that thread only.

    Voila, you now have a GUI thread that is not your main thread.


    ^Note: It is a different story on Mac OS X. Due to restrictions in the Cocoa framework, the main thread MUST be the GUI thread. The steps I outlined above will work on Windows/Linux but not on Mac. For Mac, you need to inject your code into the main thread -- see Kuba Ober's comments below.

    0 讨论(0)
  • 2020-11-29 06:48

    A good solution is found in: git@github.com:midjji/convenient_multithreaded_qt_gui.git

    then it's just e.g.

    run_in_gui_thread(new RunEventImpl([](){
            QMainWindow* window=new QMainWindow();
            window->show();
        }));
    

    callable from any thread, at any time, while taking care of setting things up for you in the bg.

    Note, this also takes care of creating a QApplication and executing it in a thread. But also works if you have already done so somewhere already.

    0 讨论(0)
提交回复
热议问题