PDA

View Full Version : Seriously Noob question: QCoreApplication::exec hangs



jbarnesweb
22nd July 2013, 19:02
Would appreciate someone's help with this newbie question.

With Qt 4.7, 4.8 and 5.0, my console application hangs when I run it. I'm expecting it to run to completion.



// from app.h
class App : public QObject
{
Q_OBJECT
public:
explicit App(QCoreApplication *app, QObject *parent = 0);

void exec()
{
emit finished();
}

signals:
void finished();

public slots:

};

// from app.cpp
App::App(QCoreApplication *app, QObject *parent) :
QObject(parent)
{
connect(this, SIGNAL(finished()), app, SLOT(quit()));
}

// from main.cpp
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

App app(&a);
app.exec();

return a.exec();
}



Why doesn't this app just immediately terminate and return control to the command line?

anda_skoa
22nd July 2013, 19:16
Why doesn't this app just immediately terminate and return control to the command line?



a.exec()

runs the Qt event loop. This does not return until quit() or exit() are called on the same object.
Since you program doesn't call either after event loop processing has started, it will continue to do event processing forever.

Cheers,
_

jbarnesweb
22nd July 2013, 19:24
Ok. Next question. Since a.exec() blocks, how do I call a.quit() after a.exec()?

ChrisW67
22nd July 2013, 22:43
From another object, ui or a timer.

The point here, however, is that you have two separate calls to exec(), only the first of which is terminated.

If you really want an application that exits immediately then don't call exec() at all, or connect a zero length timer to qApp quit()

The exec() function is not designed to be overridden (not virtual)

anda_skoa
23rd July 2013, 12:11
The point here, however, is that you have two separate calls to exec(), only the first of which is terminated.


Actually only once, the first exec() is just a normal C++ method on QObject derived class "App".
Got me confused as well :)

It is basically just a no-op, it emits a signal, which calls quit() but since the application is not running yet it doesn't do anything.

Cheers,
_

ChrisW67
24th July 2013, 00:27
I stand corrected. My brain saw "class App", assumed it sub-classed QCoreApplication, and then refused to read differently :)