QT中pushButton按下弹起3D效果

在.head头文件中添加函数设置按键和文本框

void setButton3DStyle(QPushButton *button);

void setLinedit3DStyle(QLineEdit *linedit);

在主函数中给按键或文本框设置样式,将按键或文本框的边框设置为白色或灰色并设置宽度,添加捕获按键事件的函数,将按下按键样式调整与释放状态相反,以达到3D动态效果。

void MainWindow::setButton3DStyle(QPushButton *button)
{
    QFont font("黑体", 14);
    button->setFont(font);
       // 初始样式
    button->setStyleSheet("border-top: 1px solid white;"
                          "border-left: 1px solid white;"
                          "border-right: 2px solid gray;"
                          "border-bottom: 2px solid gray;");

    // 捕获按钮的按下和释放事件
    connect(button, &QPushButton::pressed, [button]()
    {
        button->setStyleSheet("border-top: 2px solid gray;"
                              "border-left: 2px solid gray;"
                              "border-right: 1px solid white;"
                              "border-bottom: 1px solid white;");
    });

    connect(button, &QPushButton::released, [button]()
    {
        button->setStyleSheet("border-top: 1px solid white;"
                              "border-left: 1px solid white;"
                              "border-right: 2px solid gray;"
                              "border-bottom: 2px solid gray;");
    });
}

void MainWindow::setLinedit3DStyle(QLineEdit *linedit)
{
    QFont font("黑体", 14);
    linedit->setFont(font);

    linedit->setStyleSheet("border-top: 2px solid gray;"
                           "border-left: 2px solid gray;"
                           "border-right: 1px solid white;"
                           "border-bottom: 1px solid white;");
}

调用setButton3DStyle函数,将控件作为参数传递进去,使控件应用函数中的样式

setButton3DStyle(ui->pushButton);

若要将多个控件进行设置可以重复上述代码或使用下面这段代码循环遍历

QStringList buttonNames = {"clearButton", "freqButton", "openSerialButton", "sendDataButton","pushButton",
                                       "js1", "js2", "js3", "fs1", "fs2", "fs3", "OC", "OC2", "OC3", "add", "adj", };

            foreach (const QString& name, buttonNames)
            {
                QPushButton* button = ui->centralWidget->findChild<QPushButton*>(name);

                if (button)
                {
                    setButton3DStyle(button);
                }
            }

按键释放效果:

按键按下效果:

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值