109.第一个qt项目

        今天正式开始qt的学习。在安装完qt开发环境之后,下面我们来使用QtCreator创建项目。

1.创建项目

109.第一个qt项目_第1张图片

创建基于窗口的qt应用程序。109.第一个qt项目_第2张图片109.第一个qt项目_第3张图片选择编译套件, 编译套件用于项目文件的编译, 如果安装了多个编译套件, 在这里选择其中一个就可以了。109.第一个qt项目_第4张图片选择版本控制工具。109.第一个qt项目_第5张图片

 2.项目文件(.pro)

在创建的Qt项目中自动生成了一个后缀为 .pro 的项目文件,该文件中记录着项目的一些属性信息,具体信息如下:

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += 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 += \
    main.cpp \
    mainwindow.cpp \
    testwidget.cpp

HEADERS += \
    mainwindow.h \
    testwidget.h

FORMS += \
    mainwindow.ui \
    testwidget.ui

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

3.main.cpp

在这个源文件中有程序的入口函数 main(),下面给大家介绍下这个文件中自动生成的几行代码:

#include "mainwindow.h"  //生成的窗口类头文件
#include   //应用程序类头文件

int main(int argc, char *argv[])
{
    // 创建应用程序对象, 在一个Qt项目中实例对象有且仅有一个
    // 类的作用: 检测触发的事件, 进行事件循环并处理
    QApplication a(argc, argv);
    //创建窗口类对象
    MainWindow w;
    //显示窗口
    w.show();
    // 应用程序对象开始事件循环, 保证应用程序不退出
    return a.exec();
}

4.mainwindow.ui

在Qt中每一个窗口都对应一个可编辑的可视化界面(*.ui), 这个界面对应的是一个xml格式的文件, 一般情况下不需要在xml格式下对这个文件进行编辑, 关于这个文件结构了解即可。



 MainWindow
 
  
   
    0
    0
    800
    600
   
  
  
   MainWindow
  
  
  
   
    
     0
     0
     800
     28
    
   
  
  
 
 
 

5.mainwindow.h

这个文件是窗口界面对应的类的头文件。

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include // Qt标准窗口类头文件

QT_BEGIN_NAMESPACE
// mainwindow.ui 文件中也有一个类叫 MainWindow, 将这个类放到命名空间 Ui 中
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT 这个宏是为了能够使用Qt中的信号槽机制

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;// 定义指针指向窗口的 UI 对象
};
#endif // MAINWINDOW_H

6.mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)	// 基于mainwindow.ui创建一个实例对象
{
    // 将 mainwindow.ui 的实例对象和 当前类的对象进行关联
    // 这样同名的连个类对象就产生了关联, 合二为一了
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

7.运行结果

109.第一个qt项目_第6张图片

你可能感兴趣的:(QT学习,qt,开发语言)