A colour is an object representing a combination of Red, Green, and Blue (RGB) intensity values. Valid RGB values are in the range from 0 to 255. We can define a colour in various ways. The most common are RGB decimal values or hexadecimal values. We can also use an RGBA value which stands for Red, Green, Blue, and Alpha. Here we add some extra information regarding transparency. Alpha value of 255 defines full opacity, 0 is for full transparency, e.g. the colour is invisible.
代码:
# coding='utf-8'
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QColor, QBrush
import sys
class Gui(QWidget):
def __init__(self):
super(Gui, self).__init__()
self.start()
def start(self):
self.setGeometry(300, 300, 350, 100)
self.setWindowTitle('不同颜色')
self.show()
# Each time we resize the window, a paint event is generated.
def paintEvent(self, event) -> None:
qp = QPainter()
qp.begin(self)
self.draw_rectangles(event, qp)
qp.end()
def draw_rectangles(self, event, qp):
# 初始是定义成黑色
color = QColor(0, 0, 0)
# 这行相当于把前一行代码设置的黑色改成了白色
# 用进制定义一种颜色,这个好像是定义成了白色(绘出来的边框是白色)
color.setNamedColor('#d4d4d4')
# 用刚刚定义的颜色设置画笔,
# setPen用来绘制矩形等的边框,中间部分(用brush填充)不是用画笔的颜色
qp.setPen(color)
# 设置刷子:brush用来绘制一个形状图形的背景(也就是填充一个图形里面的颜色)
# 第一个QColor用的是RGB
qp.setBrush(QColor(200, 0, 0))
# 绘制的位置和大小(前两个是左上角坐标(x,y),后两个是宽度和高度)
qp.drawRect(10, 15, 90, 60)
# 这个QColor用的是RGBA,最后一个通道是Alpha通道,代表透明度\
# Alpha value of 255 defines full opacity(不透明),\
# 0 is for full transparency(透明)
qp.setBrush(QColor(250, 80, 0, 160))
# 绘制的位置和大小(前两个是左上角坐标(x,y),后两个是宽度和高度)
qp.drawRect(130, 15, 90, 60)
# 这个QColor用的是RGBA,最后一个通道是Alpha通道,代表透明度\
# Alpha value of 255 defines full opacity(不透明),\
# 0 is for full transparency(透明)
qp.setBrush(QColor(25, 0, 90, 200))
# 绘制的位置和大小(前两个是左上角坐标(x,y),后两个是宽度和高度)
qp.drawRect(250, 15, 90, 60)
app = QApplication(sys.argv)
gui = Gui()
sys.exit(app.exec_())
运行结果:
image.png
网友评论