概括:
1.创建QPushButton * btn = new QPushButton;
2.设置父亲setParent(this);
3.设置按钮文字btn->setText("wenzi")
4.移动控件move(x, y)
5.重置尺寸resize(w, h)
6.设置窗口标题setWindowText("title")
7.设置窗口固定尺寸setFixedSize(w, h)
注意:工具-选项-文本编辑器-行为-编码要设置为utf-8,否则显示可能会乱码
注意:qss书写一定要符合规范,否则会报错
一、创建QPushButton
上节代码中,我们发现,QWidget.show()之后可显示窗口,我们尝试用这种办法显示QPushButton
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>//引入QPushButton类
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) //初始化列表,该函数的声明中已有默认值
, ui(new Ui::MainWindow)
{
//新建按钮
QPushButton* btn = new QPushButton;
//显示
btn->show();
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
但是我们发现按钮此时在一个独立的窗口中显示,这是因为QWidget.show()方法是显示一个独立的窗口(在未设定parent的前提下)
可使用:btn->setParent(this);
我们使用以下代码再次尝试,结果如下图:
注意:qss书写一定要符合规范,否则会报
Could not parse stylesheet of object MainWindow(0x73fe1c)
Could not parse stylesheet of object MainWindow(0x73fe1c, name = "MainWindow")常见错误有忘记在行末尾写“;”
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>//引入QPushButton类
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) //初始化列表,该函数的声明中已有默认值
, ui(new Ui::MainWindow)
{
//新建按钮
QPushButton* btn = new QPushButton;
//设置按钮文字
btn->setText("my button");
//设置按钮父对象
btn->setParent(this);
ui->setupUi(this);
//设置样式qss
setStyleSheet("*"
"{color:white;}"
"QMainWindow"
"{background-color:rgb(50, 30, 30);}"
"QPushButton"
"{"
" padding: 15px;"
" background-color: rgb(26, 26, 26);"
" border-radius: 7px;"
" width: 80px;"
" height: 80px;"
" margin: 20px;"
" text-align: center;"
" border-top: 4px solid #fa8072;"
"}"
"QPushButton:hover"
"{background-color: rgb(15, 15, 15);}");
//重置窗口大小
//resize(500, 500);
//设置窗口标题
setWindowTitle("first window");
//设置固定窗口大小
setFixedSize(500, 500);
}
MainWindow::~MainWindow()
{
delete ui;
}
如何再添加一个按钮呢?
只需要:
QPushButton * btn = new QPushButton("btn", this);
//移动按钮,放止覆盖上一个按钮
btn->move(100, 100);