Is it possible to create local event loops without calling QApplication :: exec ()?

I would like to create a library built on top of QTcpServer and QTcpSocket for use in programs that do not have event loops in their main functions (since the Qt event loop is blocked and does not work) t provides sufficient time resolution for the required real-time operations).

I was hoping to get around this by creating local event loops inside the class, but they don't seem to work if I first called app->exec() in the main function. Is there a way to create local event loops and allow a signal / slot exchange in a stream without an event loop at the application level?

I already looked. Is there a way to use Qt without QApplication :: exec ()? , but the answer does not help, because it seems that the solution adds a local event loop, but does not delete the application loop.

+5
source share
1 answer

You can create an instance of QCoreApplication in a new thread in the library. You must check to create only one instance, because each Qt application must 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(); } } 

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

+6
source

Source: https://habr.com/ru/post/981053/


All Articles