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
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:
std::thread
(NOT a QThread
)init
function in that thread. Let it instantiate your QApplication
/QGuiApplication
and start the event loopVoila, 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.
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.