c++ - Qt 控制台应用程序中的信号和槽

标签 c++ qt qtcore qobject qt-signals

我是新手,但我想编写一个 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/

相关文章:

c++ - QT - 只用键填充 QMap,然后为每个键添加值

c++ - 如何在 QwtPlot 上给 QwtPlotCurve 添加标签?

c++ - Qt Gui 应用程序中的 2 个独立标准线程

python - pyqtSlot函数

c++ - 二进制 '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>'

c++ - 针对 V8 编译 NodeJs 模块

c++ - 使用 QDir 过滤器列出子目录中的文件

c++ - 你如何序列化一个QMap?

c++ - 如何裁剪 QComboBox 中的文本或如何获取其实际宽度?

c++ - 为 64 位 Linux 的特定 arm 目标交叉编译 Qt