qcolor pyqt5
Python hosting: Host, run, and code Python in the cloud!
Working with QColor
in PyQt5 is an essential task when developing GUI applications that require a diverse range of colors. Defining and using colors effectively can enhance the user interface of your applications.
In PyQt5, colors are primarily defined using the QColor(r, g, b)
method. This method employs the RGB color model, which stands for Red, Green, and Blue. By adjusting the values of r, g, and b, which range from 0 to 255, you can produce an extensive spectrum of colors.
Specifically, in a QPainter
widget, which is a vital widget for drawing graphics in PyQt5, you can designate a color using the setBrush
method.
For those looking to delve deeper into PyQt5 and its capabilities, consider the related course: Create GUI Apps with PyQt5.
PyQt5 Color Application Example
Below is a concise PyQt5 example that demonstrates the versatility of the QColor
method. It showcases how to draw a variety of colors on a QPainter
widget using the setBrush
and QColor
methods: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
66import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import random
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt rectangle colors - pythonspot.com'
self.left = 10
self.top = 10
self.width = 440
self.height = 280
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Set window background color
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.white)
self.setPalette(p)
# Add paint widget and paint
self.m = PaintWidget(self)
self.m.move(0,0)
self.m.resize(self.width,self.height)
self.show()
class PaintWidget(QWidget):
def paintEvent(self, event):
qp = QPainter(self)
qp.setPen(Qt.black)
size = self.size()
# Colored rectangles
qp.setBrush(QColor(200, 0, 0))
qp.drawRect(0, 0, 100, 100)
qp.setBrush(QColor(0, 200, 0))
qp.drawRect(100, 0, 100, 100)
qp.setBrush(QColor(0, 0, 200))
qp.drawRect(200, 0, 100, 100)
# Color Effect
for i in range(0,100):
qp.setBrush(QColor(i*10, 0, 0))
qp.drawRect(10*i, 100, 10, 32)
qp.setBrush(QColor(i*10, i*10, 0))
qp.drawRect(10*i, 100+32, 10, 32)
qp.setBrush(QColor(i*2, i*10, i*1))
qp.drawRect(10*i, 100+64, 10, 32)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Interested in more PyQt5 samples? Download PyQT5 Examples
For navigation:
Back | Next
Leave a Reply: