python logo

qcolor pyqt5

Python hosting: Host, run, and code Python in the cloud!

Colors in PyQt5 are defined using the method QColor(r, g, b). All colors on the screen are a combination of the red, green and blue values. Every color value should be in the range 0..255.
In a QPainter widget you can pass a color to the setBrush method.

QColor QColor example

Related course:
Create GUI Apps with PyQt5

PyQt5 color example:
This example draws a variety of colors in a QPainter widget using the setBrush and QColor methods.

import 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):
self.title = 'PyQt rectangle colors -'
self.left = 10 = 10
self.width = 440
self.height = 280

def initUI(self):
self.setGeometry(self.left,, self.width, self.height)

# Set window background color
p = self.palette()
p.setColor(self.backgroundRole(), Qt.white)

# Add paint widget and paint
self.m = PaintWidget(self)

class PaintWidget(QWidget):
def paintEvent(self, event):
qp = QPainter(self)

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()

Download PyQT5 Examples


Leave a Reply: