C++ – Suppress warning “QApplication was not created in main() thread”


I've created a Qt-based network library for use with applications that are not running a Qt event loop, and which are not necessarily otherwise Qt applications. This was made possible by creating a QCoreApplication instance in a thread per the answer from Is it possible to create local event loops without calling QApplication::exec()?

This works perfectly, but it makes Qt upset (I presume it's worried that I'll try to manipulate a GUI outside of the main thread which wouldn't work, but I'm not), and so it prints a warning: WARNING: QApplication was not created in main() thread.

I'd like to suppress that warning which will otherwise be printed to the X11 console and most likely cause my users to enter a bunch of needless deficiencies. However, I'd like to just supress THIS error, as I use qDebug for some legitimate purposes and want to see future warnings. Is there a way to do this, like some kind of Qt #pragma?


A similar question was asked before here: Qt console application "WARNING: QApplication was not created in the main() thread", but the answer was basically just a code review without any meaningful ideas to suppress the warning.

Best Solution

The problem arises because you're touching Qt APIs (in the main thread, or just in some thread) before creating QApplication. You can't do that. In particular, you're creating a QObject of some kind, which is setting somwhere in Qt what Qt itself should consider as the main thread.

The only Qt APIs you're allowed to use before creating a QApplication are the ones that are explicitely documented to be safe in that scenario.

So: don't do that. Build a QCoreApplication as the first thing, then you're free to go.

Related Question