Am I doing it right?
A client of mine has a group where I\'m developing Qt-based client-server stuff with a lot of fun widget stuff and sockets.
Another grou
Studying the Qt code it seems QCoreApplication is needed to dispatch system-wide messages such as timer events. Things like signal/slots and even QThreads do not depend on it unless they are related to those system-wide messages. Here is how I do this in a shared library (in a cross platform way using Qt itself) and I actually do call exec, because processEvents() alone does not process everything.
I have a global namespace:
// Private Qt application
namespace QAppPriv
{
static int argc = 1;
static char * argv[] = {"sharedlib.app", NULL};
static QCoreApplication * pApp = NULL;
static QThread * pThread = NULL;
};
I have an OpenApp method in a QObject (that is moc'ed) like this:
// Initialize the app
if (QAppPriv::pThread == NULL)
{
// Separate thread for application thread
QAppPriv::pThread = new QThread();
// Direct connection is mandatory
connect(QAppPriv::pThread, SIGNAL(started()), this, SLOT(OnExec()), Qt::DirectConnection);
QAppPriv::pThread->start();
}
And here is OnExec slot:
if (QCoreApplication::instance() == NULL)
{
QAppPriv::pApp = new QCoreApplication(QAppPriv::argc, QAppPriv::argv);
QAppPriv::pApp->exec();
if (QAppPriv::pApp)
delete QAppPriv::pApp;
}
So far it seems to be working fine, I am not sure if I need to delete the app at the end, I will update my answer if I find something.
The Qt Documentation for 4.5.2 says that the arguments to QCoreApplication need to have lifetimes as long as the application object - so you shouldn't really use local variables.
Apart from that little thing:
I'm grappling with the same problem, and everything seems to work for me too. I would recommend being very careful at unload / exit time, however, since if you're using the event loop from another application and that event loop is stopped before your library is unloaded then all sorts of crashy nastiness can happen when you try to close() sockets and delete QObjects.