I am writing a Windows DLL that may run under a QApplication, or may run under a regular Win32 application. I want to use the Qt Networking classes which require an event loop.
If running in a regular Win32 (non-Qt) app, I have to start a QThread or QEventLoop for the Qt networking signals and slots to work. Note: the DLL uses QtWinMigrate. But if running in a QApplication, there will already be an event loop, and no need to start a new QThread.
Is there a way to check for an existing QEventLoop?
Clarification The DLL runs under a large legacy code base, and the thread where my class is running may or may not be a QThread.
Answering for Qt 5.
You can get current QThread
by calling static function QThread::CurrentThread
. Practice has shown to me that it returns non-null pointer even if there is no QApplication
instance in your program.
The next thing to do is calling QThread::eventDispatcher
function. It returns NULL
if there is no Qt event loop in the current thread. Unfortunately, this function is available only since Qt 5. Hope there are some other ways to get the desired information in earlier versions.
By the way, I'd recommend you to start QThread
regardless of whether your code runs in a Qt or any other event loop. If there is a case when you need to spawn QThread
anyway, I'd prefer to spawn it always. Less code, less bugs.
UPDATE: In Qt 4 you can use:
QAbstractEventDispatcher::instance()
See doc.
int QThread::loopLevel() const
Returns the current event loop level for the thread. Note: This can only be called within the thread itself, i.e. when it is the current thread. This function was introduced in Qt 5.5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With