Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I determine if a thread has a QEventLoop?

Tags:

c++

qt

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.

like image 891
Matthew Avatar asked Jan 14 '16 20:01

Matthew


2 Answers

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.

like image 138
Oleg Andriyanov Avatar answered Oct 23 '22 11:10

Oleg Andriyanov


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.

like image 25
Akon Avatar answered Oct 23 '22 11:10

Akon