Qt概述(3)
四、编写第一个 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 设置内容显示位置。