当信号 QCoreApplication::quit() 在事件循环开始之前被同步触发时,该信号被忽略并且应用程序永远挂起。但是,从 QTimer 触发,应用程序正确退出。启动可以在 exec 循环开始之前立即返回的任务的正确方法是什么?
这是重现此行为的最小代码:
挂起.h
#ifndef HANG_H
#define HANG_H
#include <QObject>
class hang : public QObject
{
Q_OBJECT
public:
explicit hang(QObject *parent = 0);
signals:
void done();
public slots:
void foo();
};
#endif // HANG_H
挂起.cpp
#include "hang.h"
#include <iostream>
hang::hang(QObject *parent) :
QObject(parent)
{
}
void hang::foo()
{
std::cout << "foo emit done()" << std::endl;
emit done();
}
主文件
#include <QCoreApplication>
#include <QTimer>
#include <hang.h>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
hang obj;
QObject::connect(&obj, SIGNAL(done()), &app, SLOT(quit()));
// obj.foo() does emit done(), but app hang on exec
obj.foo();
// If done() signal is triggered from the timer, app quits correctly
//QTimer::singleShot(0, &obj, SLOT(foo()));
return app.exec();
}