Qt使用非绘制的方式简单实现一个开关按钮的思路(尺寸固定) 您所在的位置:网站首页 switch截屏键 Qt使用非绘制的方式简单实现一个开关按钮的思路(尺寸固定)

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

#Qt使用非绘制的方式简单实现一个开关按钮的思路(尺寸固定)| 来源: 网络整理| 查看: 265

效果演示在这里插入图片描述 实现思路

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

完整代码 按钮类

头文件:

#ifndef SWITCHBTNFORM_H #define SWITCHBTNFORM_H #include #include 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 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



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有