QCoreApplication
您可以在库的新线程中创建实例。您应该检查是否只创建一个实例,这是因为每个 Qt 应用程序应该只包含一个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 共享库。