問題描述
我試圖創建一個簡單的控制臺應用程序來試用 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 控制臺應用程序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!