Widget空窗口
this->setWindowTitle("我的窗口");//设置窗口标题
this->resize(500,300);//设置窗口大小
this->setFixedSize(500,300);//设置固定大小(无法拖拽)
此时,窗口大小发生改变,且窗口名称改变,窗口无法再拖动改变大小
常用的基础部件
Qt提供了很多部件,可以开发出图形化的用户界面,使用这些控件时需要先引入头文件
QLabel
常用方法:
// 创建 QLabel 对象
QLabel *l1 = new QLabel;
// 设置文本内容
l1->setText("Hello,你好啊!!!");
// 设置文本显示位置
l1->move(100, 100);
// 设置文本区域大小
l1->resize(200, 100);
// 设置文本对齐方式, 默认水平左对齐 垂直中对齐
l1->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
// 设置文本使用字体
l1->setFont(QFont("楷体"));
// 将文本框加入到父级,也就是 Widget 空窗口中
l1->setParent(this);
此时运行,在窗口内就可以显示出效果
QFont
QFont是用来设置字体的,常用方法有:
QLabel *l2 = new QLabel("QFont字体测试", this);//这是Qlabel的构造函数重载,可以直接设置内容,和指定parent,和setParent和setText这两句代码效果一致
// 设置字体
QFont font;//创建对象
font.setBold(true);//是否加粗
font.setFamily("楷体");//设置字形
font.setItalic(true);//是否倾斜
font.setPointSize(20);//设置字号
font.setWeight(QFont::Black);//设置加粗
// 设置l2应用字体
l2->setFont(font);
此时运行可以看到效果
QPushButton
是一个按钮
//方法一:
QPushButton *btn1 = new QPushButton;
btn1->setText("按钮1");
btn1->resize(80, 30);
btn1->move(50, 0);
btn1->setParent(this);
// 参数1: 按钮中的文本
// 参数2: 父组件设置
QPushButton *btn2 = new QPushButton("按钮2", this);
btn2->move(200, 0);
btn2->setFont(QFont("楷体"));
QLineEdiit
是一个单行文本框,常用的方法有
QLineEdit *txt = new QLineEdit;
txt->resize(100, 40);//设置大小
txt->setText("请输入内容");//设置文本内容
txt->resize(100, 30);
txt->move(200, 30);//移动位置
txt->setParent(this);//设置在哪个窗口
可以通过这些控件制作一个登录界面
// 窗口设置
this->setWindowTitle("游戏登录");//设置标题
this->setFixedSize(500, 300);//设置固定大小
// 请登录标题
QLabel *loginLabel = new QLabel("请登录", this);//新建一个label然后指定父和内容
loginLabel->setFont(QFont("黑体", 30, QFont::Black));//字体
loginLabel->resize(150, 50);//指定大小
loginLabel->move(177, 20);//移动位置
// 提供给账号和密码标签使用的字体
QFont f("黑体", 14);
// 账号设置
QLabel *accountLabel = new QLabel("账号:", this);
accountLabel->move(85, 98);
accountLabel->setFont(f);
QLineEdit *accoutEdit = new QLineEdit(this);
accoutEdit->move(140, 95);
accoutEdit->resize(250, 40);
accoutEdit->setPlaceholderText("账号名/手机号/邮箱");
// 密码设置
QLabel *pwdLabel = new QLabel("密码:", this);
pwdLabel->move(85, 160);
pwdLabel->setFont(f);
QLineEdit *pwdEdit = new QLineEdit(this);
pwdEdit->move(140, 155);
pwdEdit->resize(250, 40);
pwdEdit->setPlaceholderText("密码");
// setEchoMode 用来设置QLineEdit 中的文本状态
// QLineEdit::Normal: 正常状态,明文显示
// QLineEdit::Password: 密码状态, 密文显示
// QLineEdit::PasswordEchoOnEdit: 输入时明文,失焦时密文
pwdEdit->setEchoMode(QLineEdit::Password);
// 切换按钮
QPushButton *chgBtn = new QPushButton("明文", this);
chgBtn->resize(60, 40);
chgBtn->move(330, 155);
// 重置和登录按钮
QPushButton *resetBtn = new QPushButton("重置", this);
QPushButton *loginBtn = new QPushButton("登录", this);
resetBtn->resize(80, 40);
loginBtn->resize(80, 40);
resetBtn->move(135, 220);
loginBtn->move(285, 220);