如何在C ++中创建一个简单的Qt控制台应用程序? [英] How do I create a simple Qt console application in 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();
}
这篇关于如何在C ++中创建一个简单的Qt控制台应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!