DLL中的QT事件循环 [英] QT event loop in a dll

查看:690
本文介绍了DLL中的QT事件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将QT共享库与非QT c ++应用程序集成在一起. 为了处理事件,我从库中调用一个函数,该函数启动QCoreApplication,而所需的对象在单独的QThread或std :: thread中都起作用. 事件循环开始后,我需要从主线程调用创建的对象方法以从SQL数据库中获取一些数据,并且由于某些原因,它们并不总是有效. 当我在没有线程的情况下在本机QT应用程序中使用这些对象时,这永远不会发生. 我可以将问题追溯到一个函数,但是不幸的是,这是另一个封闭库的一部分. 您有什么建议可能会出问题吗?

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?

推荐答案

本机应用程序应在主线程中旋转本机事件循环. Qt在大多数平台上都使用本机事件循环,因此您不必使用QCoreApplication::exec()并在那里阻塞即可调度事件.相反,要实现良好的跨平台主线程事件循环集成,只需让事件循环旋转一次即可准备好"事件循环.这样可以确保Qt准备好由在给定线程(此处为主线程)上运行本机事件循环的任何人调度其事件.

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).

在主线程以外的任何线程上实例化QApplication都是不可移植的.它碰巧可以在Windows上运行,但根本不能在OS X上运行,它是否可以在X11上运行取决于您要与之集成的确切平台实现.

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();
}

到那时,您可以自由地启动任何QThread,这些QThread旋转其自己的事件循环并执行所需的其他任何操作.您必须确保在将要使用它们的线程中创建任何数据库访问对象.

At that point, you're free to start any QThreads 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.

这篇关于DLL中的QT事件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆