Qt学习记录--QPushButton

概括:

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);
  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值