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

How do I create a simple Qt console application in C++?(如何在 C++ 中创建一个简单的 Qt 控制台应用程序?)
本文介绍了如何在 C++ 中创建一个简单的 Qt 控制台应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我试图创建一个简单的控制台应用程序来试用 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();
}

这篇关于如何在 C++ 中创建一个简单的 Qt 控制台应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Unresolved external symbol quot;public: virtual struct QMetaObject const * __thiscall Parent(未解析的外部符号“public: virtual struct QMetaObject const * __thiscall Parent)
QVector vs QList(QVector 与 QList)
How to create/read/write JSON files in Qt5(如何在 Qt5 中创建/读取/写入 JSON 文件)
Qt: How do I handle the event of the user pressing the #39;X#39; (close) button?(Qt:如何处理用户按下“X(关闭)按钮的事件?)
STL or Qt containers?(STL 还是 Qt 容器?)
Sort filenames naturally with Qt(使用 Qt 自然地对文件名进行排序)