效果演示
实现思路
新建一个界面类,继承自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