【发布时间】:2014-04-05 07:11:27
【问题描述】:
我是新手,但我想编写一个 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();
}
【问题讨论】:
-
> 为什么在下面的代码中发出完成后执行任何操作:你能更精确吗?输出到底是什么?
-
它输出“Hello World”和“我以为我已经完成了”。我期待 Hello World,但认为完成信号与应用程序退出槽的连接会导致应用程序在“我以为我已经完成”之前终止。
标签: c++ qt qtcore qobject qt-signals