Matthew
Matthew

Reputation: 1612

Can I determine if a thread has a QEventLoop?

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.

Upvotes: 7

Views: 4646

Answers (3)

Akon
Akon

Reputation: 335

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.

Upvotes: 2

Oleg Andriyanov
Oleg Andriyanov

Reputation: 5289

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.

Upvotes: 8

Michael
Michael

Reputation: 1035

From QThread docs:

A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.

So, when you call run, it has an event loop.

Upvotes: 0

Related Questions