当前位置: 首页 > 工具软件 > SwitchButton > 使用案例 >

QT6.4制作滑动开关组件SwitchButton

田意致
2023-12-01

SwitchButton是滑动按钮组件,可开启/关闭滑动动画效果,可指定大小,可指定背景色和滑块颜色及文字颜色,可设定文字及字体。

LineSwitch是形条组件,其包含了图标+文字条+SwitchButton,可指定大小,可指定背景渐变色和文字颜色,可设定文字及字体。

源代码如下,需要自卑item0.png 和 item1.png两个图标。

SwitchButton.h


#ifndef SWITCHBUTTON_H
#define SWITCHBUTTON_H

#include <QWidget>
#include <QTimer>
#include <QColor>

class SwitchButton : public QWidget
{
    Q_OBJECT

public:
    explicit SwitchButton(QWidget *parent = 0);
    ~SwitchButton(){}

signals:
    void statusChanged(qint16 id,bool checked);

public slots:

private slots:
    void updateValue();

private:
    void drawBackGround(QPainter *painter);
    void drawSlider(QPainter *painter);

protected:
    void paintEvent(QPaintEvent *ev);
    void mousePressEvent(QMouseEvent *ev);
    void mouseReleaseEvent(QMouseEvent *ev);
    void resizeEvent(QResizeEvent *event);

private:
    qint16  m_ID;
    int     m_space;             //distance between slider and boundary
    int     m_radius;            //fillet angle

    bool    m_checked;           //switch on/off
    bool    m_showText;          //display text or not
    bool    m_showCircle;        //display circle or not
    bool    m_animation;         //use animation or not

    QColor  m_bgColorOn;         //background color when switch on
    QColor  m_bgColorOff;        //background color when switch off
    QColor  m_sliderColorOn;     //slider color when switch on
    QColor  m_sliderColorOff;    //slider color when switch off
    QColor  m_textColor;         //text color

    QString m_textOn;           //text when switch on
    QString m_textOff;          //text when switch off

    QTimer  *m_timer;           //animation timer
    int     m_step;             //animation step x pixel
    int     m_startX;           //slider start X pos
    int     m_endX;             //slider end X pos

public:
    qint16  getID();
    int     space()             const;
    int     radius()            const;
    bool    checked()           const;
    bool    showText()          const;
    bool    showCircel()        const;
    bool    animation()         const;

    QColor  bgColorOn()         const;
    QColor  bgColorOff()        const;
    QColor  sliderColorOn()     const;
    QColor  sliderColorOff()    const;
    QColor  textColor()         const;

    QString textOn()            const;
    QString textOff()           const;

    int step()                  const;
    int startX()                const;
    int endX()                  const;


public Q_SLOTS:
    void setID(qint16 id);
    void setSpace(int space);
    void setRadius(int radius);
    void setChecked(bool checked);
    void setShowText(bool show);
    void setShowCircle(bool show);
    void setAnimation(bool ok);

    void setBgColorOn(const QColor &color);
    void setBgColorOff(const QColor &color);
    void setSliderColorOn(const QColor &color);
    void setSliderColorOff(const QColor &color);
    void setTextColor(const QColor &color);

    void setTextOn(const QString &text);
    void setTextOff(const QString &text);


};



#endif

SwitchButton.cpp

#pragma execution_character_set("utf-8")
#include "SwitchButton.h"
#include <QPainter>
#include <QPainterPath>
#include <QDebug>

SwitchButton::SwitchButton(QWidget *parent) : QWidget(parent)
{
    m_ID=0;
    m_space = 2;
    m_radius = 4;
    m_checked = false;
    m_showText = true;
    m_showText = false;
    m_animation = true;

    //m_bgColorOn = QColor(97,81,233);    //紫蓝
    //m_bgColorOn = QColor(21,137,200);   //淡蓝
    m_bgColorOn = QColor(0, 204, 106);  //翠绿
    m_bgColorOff = QColor(111, 122, 126);

    m_sliderColorOn = QColor(255, 255, 255);
    m_sliderColorOff = QColor(255, 255, 255);

    m_textColor = QColor(255, 255, 255);

    m_textOn = "打开";
    m_textOff = "关闭";

    m_step = 0;
    m_startX = 0;
    m_endX = 0;

    m_timer = new QTimer(this);
    m_timer->setInterval(30);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(updateValue()));
}

void SwitchButton::drawBackGround(QPainter *painter)
{
    painter->save();
    painter->setPen(Qt::NoPen);

    QColor bgColor = m_checked ? m_bgColorOn : m_bgColorOff;
//    if (isEnabled()) {
//        bgColor.setAlpha(60);
//    }

    painter->setBrush(bgColor);

    QRect rect(0, 0, width(), height());
    int side = qMin(width(), height());

    //左侧半圆 Left semicircle
    QPainterPath path1;
    path1.addEllipse(rect.x(), rect.y(), side, side);

    //右侧半圆 Right semicircle
    QPainterPath path2;
    path2.addEllipse(rect.width() - side, rect.y(), side, side);

    //中间的矩形 Middle rectangle
    QPainterPath path3;
    path3.addRect(rect.x() + side / 2, rect.y(), rect.width() - side, height());

    QPainterPath path = path1 + path2 + path3;
    painter->drawPath(path);

    QFont font;
    font.setPointSize(height()/2);
    font.setFamily("Microsoft YaHei");
    font.setLetterSpacing(QFont::AbsoluteSpacing,0);// 设置字符间距 Set character spacing. default 0
    painter->setFont(font);
//    QFontDatabase::addApplicationFont("DEMO_FONT.TTF"); use self font
//    painter->setFont(QFont("DEMO_FONT", 34));

    //slider R
    int sliderWidth = qMin(height(), width()) - m_space * 2 - 5;
    if (m_checked){
        QRect textRect(0, 0, width() - sliderWidth, height()*0.95);
        painter->setPen(QPen(m_textColor));
        painter->drawText(textRect, Qt::AlignCenter, m_textOn);
    } else {
        QRect textRect(sliderWidth, 0, width() - sliderWidth, height()*0.95);
        painter->setPen(QPen(m_textColor));
        painter->drawText(textRect, Qt::AlignCenter, m_textOff);
    }

    painter->restore();
}

void SwitchButton::drawSlider(QPainter *painter)
{
    painter->save();
    painter->setPen(Qt::NoPen);

    QColor color = m_checked ? m_sliderColorOn : m_sliderColorOff;

    painter->setBrush(QBrush(color));

    int sliderWidth = qMin(width(), height()) - m_space * 2;
    QRect rect(m_space + m_startX, m_space, sliderWidth, sliderWidth);
    painter->drawEllipse(rect);

    painter->restore();
}

void SwitchButton::paintEvent(QPaintEvent *ev)
{
    //启用反锯齿 Enable anti aliasing
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    drawBackGround(&painter);

    drawSlider(&painter);
}

void SwitchButton::resizeEvent(QResizeEvent *event)
{
    //qDebug("resizeEvent:%d  w:%d  h:%d  %d",m_ID,width(),height(),m_space);
    m_checked = !m_checked;
    mousePressEvent(NULL);
}

void SwitchButton::mousePressEvent(QMouseEvent *ev)
{
    Q_UNUSED(ev)

    m_checked = !m_checked;
    emit statusChanged(m_ID,m_checked);

    //Calculate step long
    m_step = width() / 10;

    //Calculate the X-pos end point for slider
    if (m_checked) {
        m_endX = width() - height();
    } else {
        m_endX = 0;
    }
    //qDebug("%d step:%d  w:%d(%d)  h:%d(%d)  endX:%d",m_ID,m_step,width(),minimumWidth(),height(),minimumHeight(),m_endX);

    //use animation or not
    if (m_animation) {
        m_timer->start();
    } else{
        m_startX = m_endX;
        update();
    }
}
// 鼠标释放事件 - 切换开关状态、发射toggled()信号
void SwitchButton::mouseReleaseEvent(QMouseEvent *ev)
{
}

void SwitchButton::updateValue()
{
    if (m_checked) {
        if (m_startX < m_endX) {
            m_startX += m_step;
        } else {
            m_startX = m_endX;
            m_timer->stop();
        }
    } else {
        if (m_startX > m_endX) {
            m_startX -= m_step;
        } else {
            m_startX = m_endX;
            m_timer->stop();
        }
    }

    update();
}

qint16 SwitchButton::getID()
{
    return m_ID;
}

int SwitchButton::space() const
{
    return m_space;
}

int SwitchButton::radius() const
{
    return m_radius;
}

bool SwitchButton::checked() const
{
    return m_checked;
}

bool SwitchButton::showText() const
{
    return m_showText;
}

bool SwitchButton::showCircel() const
{
    return m_showCircle;
}

bool SwitchButton::animation() const
{
    return m_animation;
}

QColor SwitchButton::bgColorOn() const
{
    return m_bgColorOn;
}

QColor SwitchButton::bgColorOff() const
{
    return m_bgColorOff;
}

QColor SwitchButton::sliderColorOn() const
{
    return m_sliderColorOn;
}

QColor SwitchButton::sliderColorOff() const
{
    return m_sliderColorOff;
}

QColor SwitchButton::textColor() const
{
    return m_textColor;
}

QString SwitchButton::textOn() const
{
    return m_textOn;
}

QString SwitchButton::textOff() const
{
    return m_textOff;
}

int SwitchButton::step() const
{
    return m_step;
}

int SwitchButton::startX() const
{
    return m_startX;
}

int SwitchButton::endX() const
{
    return m_endX;
}


void SwitchButton::setID(qint16 id)
{
    m_ID=id;
}

void SwitchButton::setSpace(int space)
{
    if (m_space != space) {
        m_space = space;
        update();
    }
}

void SwitchButton::setRadius(int radius)
{
    if (m_radius != radius) {
        m_radius = radius;
        update();
    }
}

void SwitchButton::setChecked(bool checked)
{
    if (m_checked != checked) {
        m_checked = !checked;
        //update();
        mousePressEvent(NULL);
    }
}

void SwitchButton::setShowText(bool show)
{
    if (m_showText != show) {
        m_showText = show;
        update();
    }
}

void SwitchButton::setShowCircle(bool show)
{
    if (m_showCircle != show) {
        m_showCircle = show;
        update();
    }
}

void SwitchButton::setAnimation(bool ok)
{
    if (m_animation != ok) {
        m_animation = ok;
        update();
    }
}

void SwitchButton::setBgColorOn(const QColor &color)
{
    if (m_bgColorOn != color) {
        m_bgColorOn = color;
        update();
    }
}

void SwitchButton::setBgColorOff(const QColor &color)
{
    if (m_bgColorOff != color) {
        m_bgColorOff = color;
        update();
    }
}

void SwitchButton::setSliderColorOn(const QColor &color)
{
    if (m_sliderColorOn != color) {
        m_sliderColorOn = color;
        update();
    }
}

void SwitchButton::setSliderColorOff(const QColor &color)
{
    if (m_sliderColorOff != color) {
        m_sliderColorOff = color;
        update();
    }
}

void SwitchButton::setTextColor(const QColor &color)
{
    if (m_textColor != color) {
        m_textColor = color;
        update();
    }
}

void SwitchButton::setTextOn(const QString &text)
{
    if (m_textOn != text) {
        m_textOn = text;
        update();
    }
}

void SwitchButton::setTextOff(const QString &text)
{
    if (m_textOff != text) {
        m_textOff = text;
        update();
    }
}

LineSwitch.h
#ifndef LineSwitch_H
#define LineSwitch_H

#include <QWidget>
#include <QTimer>
#include <QColor>
#include <QLabel>

class SwitchButton;
class LineSwitch : public QWidget
{
    Q_OBJECT

public:
    explicit LineSwitch(QWidget *parent = 0);
    ~LineSwitch(){}

signals:
    void statusChanged(qint16 id,bool checked);

public slots:

private slots:
    void updateValue();

private:

protected:
    void paintEvent(QPaintEvent *ev);
    void mousePressEvent(QMouseEvent *ev);
    void mouseReleaseEvent(QMouseEvent *ev);
    void resizeEvent(QResizeEvent *event);

private:
    QColor  m_bgColorLeft,m_bgColorRight;//background color (line color)
    QColor  m_textColor;        //text color
    QLabel* m_pIcon;
    QLabel* m_pText;
    SwitchButton* m_SwitchButton;

    QTimer  *m_timer;           //animation timer

public:
    qint16  getID();
    QColor  getBgColorLeft()        const;
    QColor  getBgColorRight()        const;
    QColor  getTextColor()      const;
    QString getText()           const;
    SwitchButton* getSwitchButton() const;

public Q_SLOTS:
    void setID(qint16 id);
    void setBgColor(const QColor &colorLeft,const QColor &colorRight);
    void setTextColor(const QColor &color);
    void setText(const QString &text);
    void setIcon(const QString &ic);


public Q_SLOTS: //for SwitchButton
    void setSwSpace(int space);
    void setSwRadius(int radius);
    void setSwChecked(bool checked);
    void setSwShowText(bool show);
    void setSwShowCircle(bool show);
    void setSwAnimation(bool ok);

    void setSwBgColorOn(const QColor &color);
    void setSwBgColorOff(const QColor &color);
    void setSwSliderColorOn(const QColor &color);
    void setSwSliderColorOff(const QColor &color);
    void setSwTextColor(const QColor &color);

    void setSwTextOn(const QString &text);
    void setSwTextOff(const QString &text);

};



#endif

LineSwitch.cpp

#pragma execution_character_set("utf-8")
#include "LineSwitch.h"
#include <QPainter>
#include <QPainterPath>
#include <QDebug>
#include <QIcon>
#include <QLayout>
#include "SwitchButton.h"

LineSwitch::LineSwitch(QWidget *parent) : QWidget(parent)
{
    m_bgColorLeft = QColor(0, 210, 100);
    m_bgColorRight = Qt::blue;
    m_textColor = QColor(0, 0, 0);

    m_pIcon = new QLabel;
    m_pText = new QLabel;

//    QIcon icon = QIcon("://Resources/item0.png");
//    QPixmap m_pic = icon.pixmap(icon.actualSize(QSize(24, 24)));//size自行调整
//    m_pIcon->setPixmap(m_pic);
    m_pIcon->setFixedSize(28,28);
    QHBoxLayout* slayout = new QHBoxLayout;
    slayout->setSpacing(0);
    slayout->setContentsMargins(2,2,2,2);
    slayout->addWidget(m_pIcon);

    m_pText->setText("开启按钮滑动效果");
    QPalette pe;
    pe.setColor(QPalette::WindowText,m_textColor);
    m_pText->setPalette(pe);
    m_pText->setFixedHeight(32);
    QFont font("Microsoft YaHei", 12, 75);
    m_pText->setFont(font);

    m_SwitchButton = new SwitchButton(this);
    m_SwitchButton->setFixedSize(60,26);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->setSpacing(4);
    layout->setContentsMargins(0,0,0,0);
    layout->addLayout(slayout);
    //layout->addWidget(m_pIcon);
    layout->addWidget(m_pText);
    layout->addWidget(m_SwitchButton);
    this->setLayout(layout);

    // connect signal
    connect(m_SwitchButton, SIGNAL(statusChanged(qint16,bool)), this, SLOT(statusChanged(qint16,bool)));

    m_timer = new QTimer(this);
    m_timer->setInterval(30);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(updateValue()));
    //m_timer->start();
}

void LineSwitch::paintEvent(QPaintEvent *ev)
{
    //启用反锯齿 Enable anti aliasing
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    painter.save();
    painter.setPen(Qt::NoPen);

//    if (isEnabled()) {
//        bgColor.setAlpha(60);
//    }
    QLinearGradient linearGradient(60,50,200,200);//线性渐变
    linearGradient.setColorAt(0.0,m_bgColorLeft);
    linearGradient.setColorAt(1.0,m_bgColorRight);

//    QRadialGradient radialGradient(100,100,100,200,200);//辐射渐变
//    radialGradient.setColorAt(0.2,Qt::white);
//    radialGradient.setColorAt(0.6,Qt::green);
//    radialGradient.setColorAt(1,Qt::black);

    painter.setBrush(QBrush(linearGradient));//画刷
    //painter.setBrush(m_bgColor);

    painter.drawRoundedRect(rect(),4,4);
//    painter.setBrush(QColor(56,66,99));
//    QRect rc=m_pText->rect();rc.moveLeft(m_pText->pos().x());
//    painter.drawRect(rc);
//    qDebug("paintEvent:x:%d w:%d   x:%d w:%d  %d",m_pIcon->rect().x(),m_pIcon->rect().width(),m_pText->rect().x(),m_pText->rect().width(),m_pText->pos().x());

//    QPainterPath path;
//    path3.addRect(rect.x() + side / 2, rect.y(), rect.width() - side, height());
//    painter->drawPath(path);

    QFont font;
    font.setPointSize(height()/3);
    font.setFamily("Microsoft YaHei");
    font.setLetterSpacing(QFont::AbsoluteSpacing,0);// 设置字符间距 Set character spacing. default 0
    painter.setFont(font);
//    QFontDatabase::addApplicationFont("DEMO_FONT.TTF"); use self font
//    painter.setFont(QFont("DEMO_FONT", 34));

//    QRect textRect(0, 0, width(), height()*0.95);
//    painter.setPen(QPen(m_textColor));
//    painter.drawText(textRect, Qt::AlignCenter, m_pText->text());

    painter.restore();
}

void LineSwitch::resizeEvent(QResizeEvent *event)
{
    //qDebug("resizeEvent:%d[%d,%d]  x:%d y:%d w:%d h:%d   x:%d y:%d w:%d h:%d",m_ID,width(),height(),m_pIcon->x(),m_pIcon->y(),m_pIcon->width(),m_pIcon->height(),m_pText->x(),m_pText->y(),m_pText->width(),m_pText->height());
}

void LineSwitch::mousePressEvent(QMouseEvent *ev)
{
    Q_UNUSED(ev)
    emit statusChanged(getID(),0);
}
// 鼠标释放事件 - 切换开关状态、发射toggled()信号
void LineSwitch::mouseReleaseEvent(QMouseEvent *ev)
{
}

void LineSwitch::updateValue()
{
    update();
}


qint16 LineSwitch::getID()
{
    return m_SwitchButton->getID();
}

QColor LineSwitch::getBgColorLeft() const
{
    return m_bgColorLeft;
}
QColor LineSwitch::getBgColorRight() const
{
    return m_bgColorRight;
}

QColor LineSwitch::getTextColor() const
{
    return m_textColor;
}

QString LineSwitch::getText() const
{

}

SwitchButton* LineSwitch::getSwitchButton() const
{
    return m_SwitchButton;
}


void LineSwitch::setID(qint16 id)
{
    m_SwitchButton->setID(id);
}

void LineSwitch::setBgColor(const QColor &colorLeft,const QColor &colorRight)
{
    m_bgColorLeft=colorLeft;
    m_bgColorRight=colorRight;
}

void LineSwitch::setTextColor(const QColor &color)
{
//    if (m_textColor != color) {
//        m_textColor = color;
//        update();
//    }
}

void LineSwitch::setText(const QString &text)
{
    m_pText->setText(text);
    //update();
}
void LineSwitch::setIcon(const QString &ic)
{
    QIcon icon = QIcon(ic);
    QPixmap m_pic = icon.pixmap(icon.actualSize(QSize(28, 28)));//size自行调整
    m_pIcon->setPixmap(m_pic);
    m_pIcon->setFixedSize(28,28);
}

//-------------------------------------------------------------------------------
void LineSwitch::setSwSpace(int space)
{
    m_SwitchButton->setSpace(space);
}
void LineSwitch::setSwRadius(int radius)
{

}
void LineSwitch::setSwChecked(bool checked)
{

}
void LineSwitch::setSwShowText(bool show)
{

}
void LineSwitch::setSwShowCircle(bool show)
{

}
void LineSwitch::setSwAnimation(bool ok)
{

}

void LineSwitch::setSwBgColorOn(const QColor &color)
{

}
void LineSwitch::setSwBgColorOff(const QColor &color){

}
void LineSwitch::setSwSliderColorOn(const QColor &color)
{

}
void LineSwitch::setSwSliderColorOff(const QColor &color)
{

}
void LineSwitch::setSwTextColor(const QColor &color)
{

}

void LineSwitch::setSwTextOn(const QString &text)
{

}
void LineSwitch::setSwTextOff(const QString &text)
{

}


FrameWindow.h
#ifndef FRAMEWINDOW_H
#define FRAMEWINDOW_H

#include <QWidget>

namespace Ui {
class FrameWindow;
}

class TitleBar;
class FrameWindow : public QWidget
{
    Q_OBJECT

public:
    explicit FrameWindow(QWidget *parent = 0);
    ~FrameWindow();
    void SetWindowRectRounded();

private slots:
    void statusChanged(qint16 id,bool checked);

    void mousePressEvent(QMouseEvent * event);
    void mouseMoveEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent * event);
    void keyPressEvent(QKeyEvent *event);

private:
    Ui::FrameWindow *ui;
    //TitleBar *m_pTitleBarMain;
    //bool    m_leftMousePressed;
    //QPoint  m_StartPoint;
};

#endif
FrameWindow.cpp
#include "FrameWindow.h"
#include "ui_FrameWindow.h"
#include "QPushButton"
#include "QMouseEvent"
#include "QPainter"

FrameWindow::FrameWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FrameWindow)
{
    //set window max size
    //setWindowState(Qt::WindowMaximized);
    //remove window title bar (including maximize, minimize, and close buttons)
    //this->setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint);
    //remove maximize and minimize from window title bar,not rmove close buttons。
    //this->setWindowFlags(Qt::Dialog);

    //m_leftMousePressed = false;
    ui->setupUi(this);

    //SetWindowRectRounded(); //设置窗体圆角 不可以缩放 没有标题栏和边框

    ui->lineSwitch1->setFixedSize(280,32);
    ui->lineSwitch1->setIcon("://Resources/item0.png");
    ui->lineSwitch1->setText("开启按钮滑动效果");
    ui->lineSwitch1->setID(77);
    ui->lineSwitch1->setBgColor(QColor(253, 119, 134),QColor(151, 254, 220));
    ui->lineSwitch2->setFixedSize(280,32);
    ui->lineSwitch2->setIcon("://Resources/item1.png");
    ui->lineSwitch2->setText("大数据云存储服务");
    ui->lineSwitch2->setID(88);

    // set button min size  (tips:layout will auto adjustSize)
    ui->switchBtn1->setMinimumSize(100,40);
    ui->switchBtn2->setMinimumSize(80,30);
    ui->switchBtn3->setMinimumSize(70,20);
    ui->switchBtn1->setMaximumHeight(60);
    ui->switchBtn2->setMaximumHeight(50);
    ui->switchBtn3->setMaximumHeight(40);
    ui->switchBtn4->setMaximumHeight(30);
    ui->switchBtn5->setMaximumHeight(20);
    // set ID
    ui->switchBtn1->setID(1);
    ui->switchBtn2->setID(2);
    ui->switchBtn3->setID(3);
    ui->switchBtn4->setID(4);
    ui->switchBtn5->setID(5);
    // set color
    ui->switchBtn1->setBgColorOn(QColor(0,204,106));
    ui->switchBtn2->setBgColorOn(QColor(97,81,233));
    ui->switchBtn3->setBgColorOn(QColor(21,137,200));
    ui->switchBtn4->setBgColorOn(QColor(254,82,82));
    ui->switchBtn5->setBgColorOn(QColor(250,139,0));
    // set switch on default
    ui->switchBtn1->setChecked(true);
    ui->switchBtn2->setChecked(true);
    ui->switchBtn3->setChecked(true);
    ui->switchBtn4->setChecked(true);
    ui->switchBtn5->setChecked(true);

    // connect signal
    connect(ui->switchBtn1, SIGNAL(statusChanged(qint16,bool)), this, SLOT(statusChanged(qint16,bool)));
    connect(ui->switchBtn2, SIGNAL(statusChanged(qint16,bool)), this, SLOT(statusChanged(qint16,bool)));
    connect(ui->switchBtn3, SIGNAL(statusChanged(qint16,bool)), this, SLOT(statusChanged(qint16,bool)));
    connect(ui->switchBtn4, SIGNAL(statusChanged(qint16,bool)), this, SLOT(statusChanged(qint16,bool)));
    connect(ui->switchBtn5, SIGNAL(statusChanged(qint16,bool)), this, SLOT(statusChanged(qint16,bool)));

    connect(ui->lineSwitch1->getSwitchButton(), SIGNAL(statusChanged(qint16,bool)), this, SLOT(statusChanged(qint16,bool)));
    connect(ui->lineSwitch2->getSwitchButton(), SIGNAL(statusChanged(qint16,bool)), this, SLOT(statusChanged(qint16,bool)));

//    QList<QPushButton*> buttonList = this->findChildren<QPushButton*>("button");
//    for(int i = 0; i < buttonList.size(); i++)
//    {
//        QPushButton* tmp = buttonList.at(i);
//        tmp->setFixedSize(20,20);//all set size to 20x20
//    }

}

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

//设置窗体圆角 不可以缩放 没有标题栏和边框
void FrameWindow::SetWindowRectRounded()
{
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.drawRoundedRect(bmp.rect(),15,15);
    setMask(bmp);
}

void FrameWindow::statusChanged(qint16 id,bool checked)
{
    qDebug() << "button ID: "<< id <<" State : " << checked;
}

void FrameWindow::mousePressEvent(QMouseEvent * event)
{
    //只能是鼠标左键移动和改变大小
    if (event->button() == Qt::LeftButton)
    {
//        if (ui.widgetToolBar->underMouse())
//        {
//            m_leftMousePressed = true;
//            //按下时鼠标左键时,窗口在屏幕中的坐标
//            m_StartPoint = event->globalPos();
//        }
    }
}
void FrameWindow::mouseMoveEvent(QMouseEvent *event)
{
    //移动窗口
//    if (m_leftMousePressed)
//    {
//        QPoint curPoint = event->globalPos();   //按住移动时的位置
//        QPoint movePoint = curPoint - m_StartPoint;
//        //普通窗口
//        QPoint mainWinPos = this->pos();
//        this->move(mainWinPos.x() + movePoint.x(), mainWinPos.y() + movePoint.y());
//        m_StartPoint = curPoint;

//    }
}
void FrameWindow::mouseReleaseEvent(QMouseEvent * event)
{
    //m_leftMousePressed = false;//释放鼠标
}

void FrameWindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case Qt::Key_Escape:  // 按下的为Esc键
        qApp->quit();
        break;
    default:
        QWidget::keyPressEvent(event);
    }
}

FrameWindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>FrameWindow</class>
 <widget class="QWidget" name="FrameWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>325</width>
    <height>327</height>
   </rect>
  </property>
  <property name="focusPolicy">
   <enum>Qt::NoFocus</enum>
  </property>
  <property name="windowTitle">
   <string>SwitchButton</string>
  </property>
  <layout class="QGridLayout" name="gridLayout">
   <item row="4" column="1">
    <spacer name="verticalSpacer_2">
     <property name="orientation">
      <enum>Qt::Vertical</enum>
     </property>
     <property name="sizeHint" stdset="0">
      <size>
       <width>20</width>
       <height>100</height>
      </size>
     </property>
    </spacer>
   </item>
   <item row="0" column="0" rowspan="5">
    <spacer name="horizontalSpacer">
     <property name="orientation">
      <enum>Qt::Horizontal</enum>
     </property>
     <property name="sizeHint" stdset="0">
      <size>
       <width>140</width>
       <height>20</height>
      </size>
     </property>
    </spacer>
   </item>
   <item row="0" column="1">
    <spacer name="verticalSpacer_1">
     <property name="orientation">
      <enum>Qt::Vertical</enum>
     </property>
     <property name="sizeHint" stdset="0">
      <size>
       <width>20</width>
       <height>80</height>
      </size>
     </property>
    </spacer>
   </item>
   <item row="1" column="1">
    <widget class="LineSwitch" name="lineSwitch1" native="true">
     <property name="minimumSize">
      <size>
       <width>200</width>
       <height>20</height>
      </size>
     </property>
    </widget>
   </item>
   <item row="2" column="1">
    <widget class="LineSwitch" name="lineSwitch2" native="true">
     <property name="minimumSize">
      <size>
       <width>200</width>
       <height>20</height>
      </size>
     </property>
    </widget>
   </item>
   <item row="3" column="1" colspan="2">
    <layout class="QHBoxLayout" name="horizontalLayout_2">
     <item>
      <widget class="QLabel" name="info">
       <property name="minimumSize">
        <size>
         <width>100</width>
         <height>60</height>
        </size>
       </property>
       <property name="font">
        <font>
         <pointsize>10</pointsize>
        </font>
       </property>
       <property name="autoFillBackground">
        <bool>false</bool>
       </property>
       <property name="text">
        <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;SwitchButton是滑动按钮组件,可开启/关闭滑动动画效果,可指定大小,可指定背景色和滑块颜色及文字颜色,可设定文字及字体。&lt;/p&gt;&lt;p&gt;LineSwitch是形条组件,其包含了图标+文字条+SwitchButton,可指定大小,可指定背景渐变色和文字颜色,可设定文字及字体。&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
       </property>
       <property name="wordWrap">
        <bool>true</bool>
       </property>
      </widget>
     </item>
     <item>
      <layout class="QVBoxLayout" name="verticalLayout">
       <item>
        <widget class="SwitchButton" name="switchBtn1" native="true">
         <property name="minimumSize">
          <size>
           <width>50</width>
           <height>20</height>
          </size>
         </property>
        </widget>
       </item>
       <item>
        <widget class="SwitchButton" name="switchBtn2" native="true">
         <property name="minimumSize">
          <size>
           <width>50</width>
           <height>20</height>
          </size>
         </property>
        </widget>
       </item>
       <item>
        <widget class="SwitchButton" name="switchBtn3" native="true">
         <property name="minimumSize">
          <size>
           <width>50</width>
           <height>20</height>
          </size>
         </property>
        </widget>
       </item>
       <item>
        <widget class="SwitchButton" name="switchBtn4" native="true">
         <property name="minimumSize">
          <size>
           <width>50</width>
           <height>20</height>
          </size>
         </property>
        </widget>
       </item>
       <item>
        <widget class="SwitchButton" name="switchBtn5" native="true">
         <property name="minimumSize">
          <size>
           <width>50</width>
           <height>20</height>
          </size>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </item>
   <item row="3" column="3">
    <spacer name="horizontalSpacer_2">
     <property name="orientation">
      <enum>Qt::Horizontal</enum>
     </property>
     <property name="sizeHint" stdset="0">
      <size>
       <width>140</width>
       <height>20</height>
      </size>
     </property>
    </spacer>
   </item>
  </layout>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <customwidgets>
  <customwidget>
   <class>SwitchButton</class>
   <extends>QWidget</extends>
   <header>switchbutton.h</header>
   <container>1</container>
  </customwidget>
  <customwidget>
   <class>LineSwitch</class>
   <extends>QWidget</extends>
   <header location="global">lineswitch.h</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

最后

#include "FrameWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FrameWindow w;
w.show();
 
return a.exec();
}
 类似资料: