1,QT的编译教程

发布于:2025-06-01 ⋅ 阅读:(25) ⋅ 点赞:(0)

目录

整体流程:

1,新建project文件

2,编写源代码

3,打开QT的命令行窗口

4,生成工程文件(QT_demo.pro)

5,生成Make file

6,编译工程

7,运行编译好的可执行文件


整体流程:

1,新建project文件

新建文本文件,后缀改为.cpp

2,编写源代码

#include <QApplication>
#include <QLabel>
#include <QLineEdit>
#include <QHBoxLayout>  // 水平布局
#include <QVBoxLayout>  // 垂直布局
#include <QWidget>
#include <QPushButton>  // 添加缺失的头文件

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QLabel *infoLabel = new QLabel;
    QLabel *openLabel = new QLabel;
    QLineEdit *cmdLineEdit = new QLineEdit;
    QPushButton *commitButton = new QPushButton;
    QPushButton *cancelButton = new QPushButton;  // 修正为 QPushButton
    QPushButton *browseButton = new QPushButton;

    infoLabel->setText("input cmd:");
    openLabel->setText("open");
    commitButton->setText("commit");
    cancelButton->setText("cancel");  // 现在可以正确调用 setText
    browseButton->setText("browse");

    QHBoxLayout *cmdLayout = new QHBoxLayout;  // 水平布局对象
    cmdLayout->addWidget(openLabel);  // 修正拼写错误(addwidget -> addWidget)
    cmdLayout->addWidget(cmdLineEdit);

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(commitButton);
    buttonLayout->addWidget(cancelButton);
    buttonLayout->addWidget(browseButton);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(infoLabel);
    mainLayout->addLayout(cmdLayout);
    mainLayout->addLayout(buttonLayout);

    QWidget w;
    w.setLayout(mainLayout);
    w.show();

    return app.exec();
}

3,打开QT的命令行窗口

此时路径为安装QT程序的路径,需要进入到工程文件下

4,生成工程文件(QT_demo.pro)

QT_demo.pro 是 ​​Qt 的项目配置文件​​(类似于 CMake 的 CMakeLists.txt 或 Visual Studio 的 .vcxproj),它告诉 Qt 如何编译你的程序,包括:

  • 需要哪些 ​​Qt 模块​​(如 widgetsguicore)。
  • 哪些 ​​源文件​​ 要编译(如 .cpp 文件)。
  • 哪些 ​​头文件​​ 要包含(如 .h 文件)。
  • 如何生成 ​​可执行文件​​ 或 ​​库​​。

​​为什么需要 .pro 文件?​​

Qt 使用 qmake 工具来生成 Makefile,而 qmake 需要 .pro 文件作为输入。
​​如果没有 .pro 文件,qmake 不知道如何编译你的代码,导致 QApplication 等头文件找不到。​​

输入指令:qmake -project

注:如果失败,请添加环境变量

E:\QT_Creator\5.15.1\mingw81_64\bin

修改:

添加:  QT += widgets gui

作用:用于在 .pro 文件中指定 Qt 模块。

QT += widgets gui 的作用​​

  1. ​​widgets​​

    • 提供 GUI 组件(如 QApplicationQPushButtonQLabel 等)。
    • ​​必须添加​​,否则会报错 QApplication: No such file or directory
  2. ​​gui​​

    • 提供图形界面基础功能(如 QPainterQPixmap)。
    • 通常会自动包含在 widgets 中,但显式声明更安全。

完整的 .pro 文件示例​:

# 指定 Qt 模块(widgets 和 gui)
QT += widgets gui

# 项目类型(app 表示生成可执行程序)
TEMPLATE = app

# 生成的可执行文件名
TARGET = QT_demo

# 源文件(你的 .cpp 文件)
SOURCES += main.cpp

# 头文件(如果有)
HEADERS += widget.h

# 资源文件(如图片、qrc 文件)
RESOURCES += resources.qrc

5,生成Make file

指令:qmake

6,编译工程

指令:mingw32-make

7,运行编译好的可执行文件

双击运行QT_demo.exe即可

如果需要修改代码,只需要在修改后重新执行:mingw32-make

例如修改窗口标题名字:


网站公告

今日签到

点亮在社区的每一天
去签到