File: switch-button.cpp

package info (click to toggle)
obs-advanced-scene-switcher 1.32.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 43,492 kB
  • sloc: xml: 297,593; cpp: 147,875; python: 387; sh: 280; ansic: 170; makefile: 33
file content (102 lines) | stat: -rw-r--r-- 2,207 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "switch-button.hpp"

#include <QMouseEvent>
#include <QPainter>
#include <QPalette>

namespace advss {

static const int s_height = 20;
static const int s_innerMargin = 4;
static const int s_handleSize = s_height - s_innerMargin * 2;
static const int s_width = s_handleSize * 2 + s_innerMargin * 2;

SwitchButton::SwitchButton(QWidget *parent) : QWidget{parent}
{
	setSizePolicy({QSizePolicy::Fixed, QSizePolicy::Fixed});
	setFocusPolicy(Qt::TabFocus);
	setAttribute(Qt::WA_Hover);
}

void SwitchButton::setChecked(bool checked)
{
	if (_checked == checked) {
		return;
	}
	_checked = checked;
	emit toggled(checked);
	update();
}

bool SwitchButton::isChecked() const
{
	return _checked;
}

void SwitchButton::toggle()
{
	setChecked(!_checked);
}

QSize SwitchButton::sizeHint() const
{
	return QSize(s_width, s_height);
}

void SwitchButton::paintEvent(QPaintEvent *)
{
	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);
	QPalette pal = palette();

	if (!isEnabled()) {
		painter.setPen(pal.color(QPalette::Midlight));
		painter.setOpacity(0.5);
	} else if (_mouseDown) {
		painter.setPen(pal.color(QPalette::Light));
	} else if (underMouse() || hasFocus()) {
		painter.setPen(QPen(pal.brush(QPalette::Highlight), 1));
	} else {
		painter.setPen(pal.color(QPalette::Midlight));
	}

	if (_checked) {
		painter.setBrush(pal.color(QPalette::Button));
	}
	const qreal radius = height() / 2;
	painter.drawRoundedRect(QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5),
				radius, radius);

	// Now draw the handle
	QRect valueRect = rect().adjusted(s_innerMargin, s_innerMargin,
					  -s_innerMargin, -s_innerMargin);
	valueRect.setWidth(valueRect.height());

	if (_checked) {
		valueRect.moveLeft(width() / 2);
	}
	painter.setBrush(pal.color(QPalette::Base));
	painter.drawEllipse(valueRect);
}

void SwitchButton::mousePressEvent(QMouseEvent *event)
{
	if (event->button() == Qt::LeftButton) {
		_mouseDown = true;
	} else {
		event->ignore();
	}
}

void SwitchButton::mouseReleaseEvent(QMouseEvent *event)
{
	if (event->button() == Qt::LeftButton && _mouseDown) {
		_mouseDown = false;
		toggle();
		emit checked(_checked);
	} else {
		event->ignore();
	}
}

} // namespace advss