QT学习遇到的问题(1)

来源:互联网 发布:网络与高性能计算 编辑:程序博客网 时间:2024/06/04 17:49

代码如下

#include <QCoreApplication>

#include <QLabel>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc,argv);
    QLabel *label = new QLabel("Hello Qt!");
    label->show();
    return a.exec();
}


在QTCreator中编译没有问题,但是在执行的时候报错:

QWidget: Cannot create a QWidget when no GUI is being used


经过在网上的查找求证,将代码更改如下即可编译通过:

#include <QApplication>

#include <QLabel>
int main(int argc, char *argv[])
{
    QApplication a(argc,argv);
    QLabel *label = new QLabel("Hello Qt!");
    label->show();
    return a.exec();
}

那么QApplication 与 QCoreApplication之间的区别是什么呢?

根据QT reference Documention的说明,得知:

这两者的最主要的区别是,

QCoreApplication用于non-GUI的应用程序(不需要依赖QtGui库),QApplication用于包含GUI的应用程序(需要用到QtGui库)。




QCoreApplication

the QCoreApplication class provides an event loop for console Qt applications.

This class is used by non-GUI applications to provide their event loop. For non-GUI application that uses Qt, there should be exactly one QCoreApplication object. For GUI applications, seeQApplication.

QCoreApplication contains the main event loop, where all events from the operating system (e.g., timer and network events) and other sources are processed and dispatched. It also handles the application's initialization and finalization, as well as system-wide and application-wide settings.


QApplication

The QApplication class manages the GUI application's control flow and main settings.

QApplication contains the main event loop, where all events from the window system and other sources are processed and dispatched. It also handles the application's initialization, finalization, and provides session management. In addition, QApplication handles most of the system-wide and application-wide settings.

For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time. For non-GUI Qt applications, useQCoreApplication instead, as it does not depend on theQtGui library.

The QApplication object is accessible through the instance() function that returns a pointer equivalent to the global qApp pointer.




原创粉丝点击