自定义Qt滑动开关按钮SwitchForm

概述

这是一个自定义的Qt滑动开关按钮SwitchForm,它提供了以下功能:

  • 自定义外观:可以设置按钮的颜色、圆角、文本等属性。
  • 动画效果:支持开启或关闭状态切换时的动画效果。
  • 状态切换信号:当按钮状态发生改变时,会发出statusChanged信号。

使用方法

  1. 在Qt项目中包含switchform.h头文件。
  2. 创建SwitchForm类的实例,并设置按钮的属性。
  3. 连接statusChanged信号到相应的槽函数,以处理按钮状态的变化。

示例代码

// 创建SwitchForm实例
SwitchForm *switchForm = new SwitchForm(this);

// 设置按钮属性
switchForm->setSpace(5);

switchForm->setRadius(10);

switchForm->setChecked(true);

switchForm->setShowText(true);

switchForm->setAnimation(true);

switchForm->setBgColorOn(QColor(102, 205, 170));

switchForm->setBgColorOff(QColor(190, 190, 190));

switchForm->setSliderColorOn(QColor(255, 255, 255));

switchForm->setSliderColorOff(QColor(255, 255, 255));

switchForm->setTextColor(QColor(255, 255, 255));

switchForm->setTextOn('开启');

switchForm->setTextOff('关闭');

// 连接状态切换信号
connect(switchForm, &SwitchForm::statusChanged, this, &MyWidget::onSwitchStatusChanged);

// 槽函数
void MyWidget::onSwitchStatusChanged(bool checked)
{
    if (checked) {
        // 处理按钮开启状态
    } else {
        // 处理按钮关闭状态
    }
}

获取按钮状态

可以使用checked()方法获取按钮的当前状态,如下所示:

bool isChecked = switchForm->checked();

在其他界面使用

如果要在其他界面使用SwitchForm类的getStatus()函数,需要在该界面中包含switchform.h头文件,并调用SwitchForm类的静态函数getStatus(),如下所示:

#include 'switchform.h'

bool status = SwitchForm::getStatus();

这样就可以获取SwitchForm类中的状态值了。

自定义Qt滑动开关按钮SwitchForm

原文地址: http://www.cveoy.top/t/topic/fAS0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录