简体   繁体   中英

QT event loop in a dll

I have to integrate QT shared library with a non QT c++ application. To process events, I call a function from the library, which starts the QCoreApplication, and the needed objects in a separate QThread or std::thread, both works. After the event loop started, I need to call the created object methods from the main thread to get some data from an SQL database and for some reason, they are not always working. That never happens, when I use these objects in a native QT application, without threading. I can trace the problem to a function, but unfortunately, that is part of another closed library. Do you have any suggestions what could go wrong?

The native application should be spinning a native event loop in the main thread. Qt uses the native event loop on most platforms, so you don't have to use QCoreApplication::exec() and block there to dispatch events. Instead, to have a decent cross-platform main thread event loop integration just "prime" the event loop by letting it spin once. This ensures that Qt is ready to have its events dispatched by whoever runs the native event loop on a given thread (here: main thread).

It is non-portable to instantiate QApplication on any thread but the main thread. It happens to work on Windows, but it won't work on OS X at all, and whether it works on X11 depends on what exact platform implementation you're integrating with.

static std::unique_ptr<QApplication> app;
static int argc{1};
static const char * argv[] = { "myLibrary", nullptr };

void myLibraryInit() {
   app.reset(new QApplication{argc, argv});
   QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
   app.exec();
}

void myLibraryDeInit() {
   app.reset();
}

At that point, you're free to start any QThread s that spin their own event loops and do whatever else that's needed. You have to make sure that any database access objects are created in the thread where they'll be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM