在.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);
}
}
按键释放效果:
按键按下效果: