-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathcolorbutton.py
More file actions
66 lines (49 loc) · 1.77 KB
/
colorbutton.py
File metadata and controls
66 lines (49 loc) · 1.77 KB
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
import sys
if "PySide6" in sys.modules:
from PySide6 import QtGui, QtWidgets
from PySide6.QtCore import Qt, Signal
elif "PyQt5" in sys.modules:
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSignal as Signal
else:
from PySide2 import QtGui, QtWidgets
from PySide2.QtCore import Qt, Signal
class ColorButton(QtWidgets.QPushButton):
'''
Custom Qt Widget to show a chosen color.
Left-clicking the button shows the color-chooser, while
right-clicking resets the color to the default color (None by default).
'''
colorChanged = Signal(object)
def __init__(self, *args, color=None, **kwargs):
super(ColorButton, self).__init__(*args, **kwargs)
self._color = None
self._default = color
self.pressed.connect(self.onColorPicker)
# Set the initial/default state.
self.setColor(self._default)
def setColor(self, color):
if color != self._color:
self._color = color
self.colorChanged.emit(color)
if self._color:
self.setStyleSheet("background-color: %s;" % self._color)
else:
self.setStyleSheet("")
def color(self):
return self._color
def onColorPicker(self):
'''
Show color-picker dialog to select color.
Qt will use the native dialog by default.
'''
dlg = QtWidgets.QColorDialog(self)
if self._color:
dlg.setCurrentColor(QtGui.QColor(self._color))
if dlg.exec_():
self.setColor(dlg.currentColor().name())
def mousePressEvent(self, e):
if e.button() == Qt.RightButton:
self.setColor(self._default)
return super(ColorButton, self).mousePressEvent(e)