Qt使用非绘制的方式简单实现一个开关按钮的思路(尺寸固定)

效果演示在这里插入图片描述

实现思路

新建一个界面类,继承自QWidget,在其中放置一个Widget作为按钮背景,两个label,一个用作开关圆圈,一个用作文字显示,计算出它们分别在“开”和“关”状态下的合理位置,使用mousePressEvent实现点击时的状态切换和位置移动;

完整代码

按钮类

头文件:

#ifndef SWITCHBTNFORM_H
#define SWITCHBTNFORM_H

#include <QWidget>
#include <QMouseEvent>

namespace Ui {
class SwitchBtnForm;
}

class SwitchBtnForm : public QWidget
{
    Q_OBJECT

public:
    explicit SwitchBtnForm(QWidget *parent = nullptr);
    ~SwitchBtnForm();
protected:
    void mousePressEvent(QMouseEvent *event);
public:
    void setTextLabPos(int xPos, int yPos); // 设置文字在按钮中的显示位置
private:
    Ui::SwitchBtnForm *ui;
    bool switchState = false; // 开关默认状态为关
};

#endif // SWITCHBTNFORM_H

源文件:

#include "switchbtnform.h"
#include "ui_switchbtnform.h"
#include <QFont>

constexpr int edgeNum = 2;
constexpr int edgeSpace = 5;

SwitchBtnForm::SwitchBtnForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SwitchBtnForm)
{
    ui->setupUi(this);
    QFont tipFont;
    tipFont.setFamily("SimSun");
    ui->tipLabel->setText("关");
}

SwitchBtnForm::~SwitchBtnForm()
{
    delete ui;
}

void SwitchBtnForm::mousePressEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    int xDistance = 0;
    const QString offBgWidgetStyle = "QWidget#bgWidget{background: rgb(173, 173, 173);\
            border: 0px;border-radius: 20px;}";
    const QString onBgWidgetStyle = "QWidget#bgWidget{background:#1E90FF;\
            border: 0px;border-radius: 20px;}";

    if (!switchState) {
        xDistance = ui->bgWidget->width() - ui->label->width() - edgeSpace * edgeNum;
        ui->label->move(ui->label->pos().x() + xDistance, edgeSpace);
        ui->tipLabel->move(ui->bgWidget->width() / edgeNum - ui->tipLabel->width(), 0);
        ui->bgWidget->setStyleSheet(onBgWidgetStyle);
        ui->tipLabel->setText("开");
        switchState = true;
    } else {
        ui->label->move(edgeSpace, edgeSpace);
        ui->tipLabel->move(ui->bgWidget->width() / edgeNum, 0);
        ui->bgWidget->setStyleSheet(offBgWidgetStyle);
        ui->tipLabel->setText("关");
        switchState = false;
    }
}

void SwitchBtnForm::setTextLabPos(int xPos, int yPos)
{
    ui->tipLabel->setGeometry(xPos, yPos, 20, 40);
}

界面文件:
在这里插入图片描述

主界面类中拖入一个QWidget,将其尺寸设置为与SwitchBtnForm一致,提升该widget为SwitchBtnForm类即可;

# 完整代码下载地址
https://download.csdn.net/download/qq_44896246/87514790

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值