原文链接
前言
在Qt中处理用户界面的时候,常常需要给用户一个是否开启某个功能的选项。但是自带的几个可以实现组件都有点丑,比如QCheckBox或QRadioButton之类,即使使用样式调整,默认的操作逻辑还是过于复古,所以这里我们用一个最简单的方法实现,不需要创建新类(当然,为了方便调用,也可以创建)
实现
本质上是使用PushButton的左右移动来模拟Switch标点的运动,示例代码如下:
QPushButton *wiredDhcpInput = nullptr;
int wiredDhcpValue = 0;
wiredDhcpInput = new QPushButton("⬤", wiredDhcp);
wiredDhcpInput->setStyleSheet(SWITCH_BUTTON_DISABLE_STYLE);
connect(wiredDhcpInput, &QPushButton::clicked, this,
[=] {
wiredDhcpValue = wiredDhcpValue ? 0 : 1;
wiredDhcpInput->setStyleSheet(wiredDhcpValue
? SWITCH_BUTTON_ENABLE_STYLE
: SWITCH_BUTTON_DISABLE_STYLE);
});
使用⬤来伪装Switch中间那个圆圈,当然也可以选择其他字符,但是需要实心且受文本颜色影响,比如⚪这种就不能被接受,风格代码如下:
constexpr auto SWITCH_BUTTON_ENABLE_STYLE = R"(
QPushButton {
background-color: rgb(50, 215, 75);
color: white;
margin-right: 20px;
padding-left: 3px;
padding-right: 3px;
padding-top: 0px;
padding-bottom: 3px;
font-size: 22px;
width: 40px;
height: 22px;
text-align: right;
border-radius: 10px;
}
QPushButton:focus {
outline: none;
}
)";
constexpr auto SWITCH_BUTTON_DISABLE_STYLE = R"(
QPushButton {
background-color: rgb(61, 61, 61);
color: white;
margin-right: 20px;
padding-left: 3px;
padding-right: 3px;
padding-top: 0px;
padding-bottom: 3px;
font-size: 22px;
width: 40px;
height: 22px;
text-align: left;
border-radius: 10px;
}
QPushButton:focus {
outline: none;
}
)";
具体宽高和留边内嵌小伙伴可以根据自身项目调整,最后得到效果为:


当加载数据时候:
if (wiredDhcpInput) {
wiredDhcpInput->setStyleSheet(g_netWiredDhcp ? SWITCH_BUTTON_ENABLE_STYLE : SWITCH_BUTTON_DISABLE_STYLE);
wiredDhcpValue = g_netWiredDhcp;
}
保存数据的时候:
if (g_netWiredDhcp != wiredDhcpValue) {
g_netWiredDhcp = wiredDhcpValue;
// Save to db ...
}
3592

被折叠的 条评论
为什么被折叠?



