所在位置:首页 → 编程语言 → C++ → 一个最简单的Qt应用程序(Qt基础文件解析)

一个最简单的Qt应用程序(Qt基础文件解析)

发布: 更新时间:2023-01-05 00:00:06

根据上文的《使用Qt Creator创建项目》,我们创建了一个最简单的QT项目。生成的文件内容如下,本文将带大家解析一下这些文件。

一、main.cpp

#include "mainwindow.h"

#include <QApplication>    # Qt系统提供的类头文件没有.h后缀

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

解析:

  • Qt一个类对应一个头文件,类名和头文件名一致
  • QApplication应用程序类
    • 管理图形用户界面应用程序的控制流和主要设置。
    • 是Qt生命,一个程序要确保一直运行,就肯定至少得有一个循环,这就是Qt主消息循环,在其中完成来自窗口系统和其它资源的所有事件消息处理和调度。它也处理应用程序的初始化和结束,并且提供对话管理
    • 对于任何一个使用Qt的图形用户界面应用程序,都正好存在一个QApplication 对象,不论这个应用程序在同一时刻有多少个窗口。
  • a.exec()

程序进入消息循环,等待对用户输入进行响应。这里main()把控制权转交给Qt,Qt完成事件处理工作,当应用程序退出的时候exec()的值就会返回。在exec()中,Qt接受并处理用户和系统的事件并且把它们传递给适当的窗口部件。

二、类头文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    //引入Qt信号和槽机制的一个宏
    Q_OBJECT

public:
    //构造函数中parent是指父窗口
    //如果parent是0,那么窗口就是一个顶层的窗口
    MainWindow(QWidget *parent = nullptr); 
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

三、.pro文件

.pro就是工程文件(project),它是qmake自动生成的用于生产makefile的配置文件。类似于VS中的.sln 和vsproj文件

QT       += core gui      //引入哪些模块

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets   //QT4以上版本还有引入widgets

CONFIG += c++11   //使用c++11的特性(qt5.6以上版本默认使用C++11)

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \            //工程中包含的源文件(\为换行,Qt为单行解析)
    main.cpp \        
    mainwindow.cpp

HEADERS += \            //工程中包含的头文件
    mainwindow.h

FORMS += \              //工程中包含的.ui设计文件
    mainwindow.ui

TRANSLATIONS += \       //工程中包含的翻译文件
    untitled_zh_CN.ts

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

在这里使用“+=”,是因为我们添加我们的配置选项到任何一个已经存在中。这样做比使用“=”那样替换已经指定的所有选项更安全。

标签:, , ,
文章排行