是否可以在不调用QApplication :: exec()的情况下创建本地事件循环? [英] Is it possible to create local event loops without calling QApplication::exec()?

查看:91
本文介绍了是否可以在不调用QApplication :: exec()的情况下创建本地事件循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个建立在 QTcpServer QTcpSocket 之上的库,以用于在 main <中没有事件循环的程序中使用/code>函数(因为Qt事件循环正在阻塞并且没有为所需的实时操作提供足够的时间分辨率).

I'd like to create a library built on top of QTcpServer and QTcpSocket for use in programs that don't have event loops in their main functions (because the Qt event loop is blocking and doesn't provide enough timing resolution for the real-time operations required).

我希望通过在类内创建本地事件循环来解决此问题,但是除非我在主函数中调用了 app-> exec(),否则它们似乎无法正常工作第一的.有什么方法可以创建本地事件循环,并允许线程内的信号/插槽通信,而无需应用程序级事件循环?

I was hoping to get around this by creating local event loops within the class, but they don't seem to work unless I've called app->exec() in the main function first. Is there some way to create local event loops and allow for signal/slot communication within a thread without having an application level event loop?

我已经看过>有没有办法在没有QApplication :: exec()的情况下使用Qt,但是答案没有帮助,因为该解决方案似乎添加了本地事件循环,但并没有删除应用程序循环.

I've already looked at Is there a way to use Qt without QApplication::exec()? but the answer doesn't help because it seems like the solution adds a local event loop but doesn't remove the application loop.

推荐答案

您可以在库中的新线程中创建 QCoreApplication 的实例.您应该检查仅创建一个实例,这是因为每个Qt应用程序应仅包含一个 QCoreApplication :

You can create the instance of the QCoreApplication in a new thread in the library. You should check to create only one instance of it, That's because each Qt application should contain only one QCoreApplication :

class Q_DECL_EXPORT SharedLibrary :public QObject    
{
Q_OBJECT
public:
    SharedLibrary();

private slots:

    void onStarted();

private:
    static int argc = 1;
    static char * argv[] = {"SharedLibrary", NULL};
    static QCoreApplication * app = NULL;
    static QThread * thread = NULL;
};


SharedLibrary::SharedLibrary()
{
    if (thread == NULL)
    {
        thread = new QThread();
        connect(thread, SIGNAL(started()), this, SLOT(onStarted()), Qt::DirectConnection);
        thread->start();
    }
}
SharedLibrary::onStarted()
{
   if (QCoreApplication::instance() == NULL)
   {
       app = new QCoreApplication(argc, argv);
       app->exec();
   }
}  

这样,即使在非Qt应用程序中,您也可以使用Qt共享库.

This way you can use your Qt shared library even in non Qt applications.

这篇关于是否可以在不调用QApplication :: exec()的情况下创建本地事件循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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