問(wèn)題描述
我試圖創(chuàng)建一個(gè)簡(jiǎn)單的控制臺(tái)應(yīng)用程序來(lái)試用 Qt 的 XML 解析器.我在VS2008開(kāi)始了一個(gè)項(xiàng)目,得到了這個(gè)模板:
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();
}
因?yàn)槲也恍枰录幚恚晕蚁胫廊绻液雎詣?chuàng)建一個(gè) QCoreApplication 并運(yùn)行事件循環(huán),我是否會(huì)遇到麻煩.文檔說(shuō)明在大多數(shù)情況下建議使用它.
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.
然而,出于好奇,我想知道如何在事件循環(huán)上執(zhí)行一些通用任務(wù),然后終止應(yīng)用程序.我無(wú)法用谷歌搜索相關(guān)示例.
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.
推薦答案
如果您希望事件循環(huán)運(yùn)行,這里有一種簡(jiǎn)單的方法可以構(gòu)建應(yīng)用程序.
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();
}
這篇關(guān)于如何在 C++ 中創(chuàng)建一個(gè)簡(jiǎn)單的 Qt 控制臺(tái)應(yīng)用程序?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!