我是新手,但我想写一个Qt控制台应用程序,它使用Qt的功能,包括信号和插槽,因此需要一个应用程序事件循环。关注这个问题How do I create a simple Qt console application in C++?我似乎朝着正确的方向前进,但为什么在发出以下代码完成后会执行任何操作:
// main.cpp
#include <QtCore>
#include <QDebug>
class Task : public QObject
{
Q_OBJECT
public:
Task(QObject *parent = 0) : QObject(parent) {}
public slots:
void run()
{
// Do processing here
qDebug() << "Hello World";
emit finished();
qDebug() << "I thought I'd finished!";
}
signals:
void finished();
};
#include "main.moc"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Task parented to the application so that it
// will be deleted by the application.
Task *task = new Task(&a);
// This will cause the application to exit when
// the task signals finished.
QObject::connect(task, SIGNAL(finished()), &a, SLOT(quit()));
// This will run the task from the application event loop.
QTimer::singleShot(0, task, SLOT(run()));
return a.exec();
}
答案 0 :(得分:2)
尝试继承QCoreApplication,并在插入调试打印时重新实现quit()信号。
如果使用DirectConnection
,您将看到在“运行”广告位中第二次打印之前立即调用退出函数。
另外,根据文档,quit()与GNU C exit()略有不同,值得一提:
请注意,与同名的C库函数不同,此函数会返回调用者 - 事件处理会停止。
这意味着quit()dos并不意味着应用程序立即退出而不会在方法执行过程中正常终止。