How to create a Qt shared library for a non-Qt application

一曲冷凌霜 提交于 2019-12-01 05:56:07

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.

So your library can be like :

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

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

I guess you need to use static linkage with Qt library. It requires you to get or create static Qt library build and then use it to compile your shared library.

StefanB

I just resolved the same issue and I'm able to have a QApplication entirely encapsulated in a DLL (Qt 5.8) that is loaded and called from a non-Qt (Delphi) application.

I followed the code sample from @Nejat. However this didn't work for me, any Qt GUI in that thread was shown, but blocked.

I wasn't able to resolve this using QApplication::processEvents() and I assume a conflict with QThread.

The solution was NOT to use a QThread for QApplication but to use the Win32 CreateThread function and create a "non qt" thread. Thus there is also no need to have SharedLibrary to be a QObject.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!