raDIYo 0.4
swswitch.cpp
1/***************************************************************************
2
3 source::worx raDIYo
4 Copyright © 2020-2022 c.holzheuer
5 c.holzheuer@sourceworx.org
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12***************************************************************************/
13
14/*
15
16 Written by viv. mail: viv.rajkumar@hotmail.com
17 @see https://stackoverflow.com/questions/14780517/toggle-switch-in-qt/51023362
18
19*/
20
21#include <QPainter>
22#include <QDebug>
23#include <QMouseEvent>
24
25#include <swswitch.h>
26
27
28SWSwitch::SWSwitch( QWidget* parent )
29 : QAbstractButton( parent ),
30 _isOn( false ),
31 _opacity( 0.000 ),
32 _height( 16 ),
33 _margin( 3 ),
34 //_thumb( QColor( 200,200,200 ) ),
35 _thumb( Qt::lightGray ),
36 _anim( new QPropertyAnimation( this, "offset", this ) )
37{
38
39 setOffset( _height / 2 );
40 _y = _height / 2;
41 setBrush( Qt::green );
42 setBrush( QColor( 242,242,242 ) );
43}
44
45
46void SWSwitch::paintEvent( QPaintEvent* event )
47{
48 Q_UNUSED( event );
49
50 QPainter painter( this );
51 painter.setPen( Qt::NoPen );
52 QRect bounding( _margin, _margin, width() - 2 * _margin, height() - 2 * _margin );
53 QRectF ecl( offset() - (_height / 2), _y - (_height / 2), height(), height() );
54 double rd = 8.0;
55
56 if( isEnabled() )
57 {
58 painter.setBrush( _isOn ? brush() : Qt::white );
59 painter.setOpacity( _isOn ? 0.5 : 0.38 );
60 painter.setRenderHint( QPainter::Antialiasing, true );
61
62 painter.drawRoundedRect( bounding, rd, rd );
63 painter.setBrush( _thumb );
64 painter.setOpacity( 1.0 );
65 painter.drawEllipse( ecl );
66 return;
67 }
68
69 painter.setBrush( Qt::black );
70 painter.setOpacity( 0.12 );
71 painter.drawRoundedRect( bounding, rd, rd );
72 painter.setOpacity( 1.0) ;
73 painter.setBrush( Qt::white );
74 painter.drawEllipse( ecl );
75
76}
77
78
79void SWSwitch::mouseReleaseEvent( QMouseEvent* event )
80{
81 if( event->button() & Qt::LeftButton )
82 {
83 _isOn = !_isOn;
84 _thumb = _isOn ? _brush : QBrush( Qt::lightGray );
85
86 if( _isOn )
87 {
88 qDebug() << "am einschalten";
89 _anim->setStartValue( _height / 2 );
90 _anim->setEndValue( width() - _height );
91 _anim->setDuration( SWANIMDURATION );
92 _anim->start();
93 }
94 else
95 {
96 _anim->setStartValue( offset() );
97 _anim->setEndValue( _height / 2 );
98 _anim->setDuration( SWANIMDURATION );
99 _anim->start();
100 }
101 }
102 QAbstractButton::mouseReleaseEvent( event );
103}
104
105
106void SWSwitch::enterEvent( QEvent *event )
107{
108 setCursor( Qt::PointingHandCursor );
109 QAbstractButton::enterEvent( event );
110}
111
112
113QSize SWSwitch::sizeHint() const
114{
115 return QSize( 2 * (_height + _margin), _height + 2 * _margin );
116}