如何在 C++ 中创建一个简单的 Qt 控制台应用程序?

2021-12-09 00:00:00 qt console c++

我试图创建一个简单的控制台应用程序来试用 Qt 的 XML 解析器.我在VS2008开始了一个项目,得到了这个模板:

I was trying to create a simple console application to try out Qt's XML parser. I started a project in VS2008 and got this template:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    return a.exec();
}

因为我不需要事件处理,所以我想知道如果我忽略创建一个 QCoreApplication 并运行事件循环,我是否会遇到麻烦.文档说明在大多数情况下建议使用它.

Since I don't need event processing, I was wondering whether I may get into trouble if I neglect to create a QCoreApplication and running the event loop. The docs state that it's recommended in most cases.

然而,出于好奇,我想知道如何在事件循环上执行一些通用任务,然后终止应用程序.我无法用谷歌搜索相关示例.

For the sake of curiosity however, I am wondering how could I make some generic task execute on the event loop and then terminate the application. I was unable to google a relevant example.

推荐答案

如果您希望事件循环运行,这里有一种简单的方法可以构建应用程序.

Here is one simple way you could structure an application if you want an event loop running.

// main.cpp
#include <QtCore>

class Task : public QObject
{
    Q_OBJECT
public:
    Task(QObject *parent = 0) : QObject(parent) {}

public slots:
    void run()
    {
        // Do processing here

        emit 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();
}

相关文章