四、编写第一个 Qt 程序
4.1 使用按钮实现
(1)纯代码方式实现
在 widget.cpp 中引入 QPushButton 控件的头文件,创建按钮对象,通过 setText 设置按钮上显示的文本,再用 setParent 将按钮挂载到窗口上。
#include "widget.h" #include "ui_widget.h" #include <QPushButton> //添加"按钮"控件的头文件 Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); QPushButton *btn = new QPushButton; //创建按钮 btn->setText("Hello_Qt"); //在"按钮"上显示"Hello Qt" btn->setParent(this); //将按钮置于窗口上 }(2)可视化操作实现
先双击 widget.ui 文件进入设计模式,再从组件选择窗口拖拽按钮控件至 UI 界面窗口并修改其内容,最后构建并运行即可看到效果。
4.2 使用标签实现
(1)纯代码方式实现
标签的纯代码实现同样在 widget.cpp 中进行:引入 QLabel 和 QFont 头文件,创建标签对象,设置标签文本与窗口大小,再通过 QFont 设置字体,用 move 指定标签位置,用 setStyleSheet 设置字体颜色。
#include "widget.h" #include "ui_widget.h" #include <QLabel> //添加"标签"头文件 #include <QFont> //添加"字体"头文件 Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); QLabel *lab = new QLabel(this); //创建标签 lab->setText("中华人民共和国万岁"); //设置标签内容 setFixedSize(1000, 900); //设置窗口大小 //设置字体 QFont font("华文行楷", 64); lab->setFont(font); //设置标签内容显示的位置 lab->move(0, 300); //设置标签字体颜色 lab->setStyleSheet("color:blue"); }运行后窗口中会按设置显示相应样式的文字内容。
(2)可视化操作实现
双击 widget.ui 文件进入设计模式,拖拽标签至 UI 设计界面中,双击修改标签内容;在右侧属性面板中可通过 styleSheet 设置字体颜色,通过 alignment 设置内容显示位置。