QT中实现类似苹果的Switch风格按钮

原文链接

欢迎大家对于本站的访问 - AsterCasc

前言

Qt中处理用户界面的时候,常常需要给用户一个是否开启某个功能的选项。但是自带的几个可以实现组件都有点丑,比如QCheckBoxQRadioButton之类,即使使用样式调整,默认的操作逻辑还是过于复古,所以这里我们用一个最简单的方法实现,不需要创建新类(当然,为了方便调用,也可以创建)

实现

本质上是使用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 ...
}

原文链接

欢迎大家对于本站的访问 - AsterCasc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值