我是新手,但我想编写一个 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();
}
最佳答案
尝试子类化 QCoreApplication 并通过插入调试打印重新实现 quit() 信号。
如果您使用的是 DirectConnection
,您将看到在“运行”槽中第二次打印之前立即调用了 quit 函数。
此外,根据文档,quit() 与 GNU C exit() 略有不同:
Note that unlike the C library function of the same name, this function does return to the caller -- it is event processing that stops.
这意味着 quit() 并不意味着应用程序在您的方法执行过程中没有正常终止就立即退出。
关于c++ - Qt 控制台应用程序中的信号和槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22877797/