有没有正确的方法来孵化 QLabel

Is there a proper way to hatch QLabel

如标题中所述,我确实想知道是否有正确的方法来孵化 QLabel,在我的例子中,它具有 QRect 的几何形状,如您在我的文章中所见.

我检查了 documentation 但我不明白如何孵化 QLabel

这是 QLabel 孵化后的样子(不同的选项):

注意:我不打算加载 QPixmap,我正在寻找更简洁的方法。

您可以覆盖 QLabelpaintEvent 并将 QBrush 与预定义的 BrushStyle pattern 一起使用,或者将您的模式定义为微小的像素图并用作QBrush.

如果您需要在文本上方(作为前景)绘制图案,请在绘制之前调用 super().paintEvent(event),如果您需要在文本下方(作为背景)调用 super().paintEvent(event)

from PyQt5 import QtWidgets, QtGui, QtCore

class LabelStandardPattern(QtWidgets.QLabel):

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.save()
        painter.setPen(QtCore.Qt.NoPen)
        painter.setBrush(QtGui.QBrush(QtCore.Qt.Dense6Pattern))
        painter.drawRect(self.rect())
        painter.restore()
        super().paintEvent(event)


class LabelUserPattern(QtWidgets.QLabel):

    def __init__(self, text="", parent = None):
        super().__init__(text, parent)
        image = QtGui.QImage(5,5, QtGui.QImage.Format_ARGB32)
        image.fill(QtCore.Qt.transparent)
        painter = QtGui.QPainter(image)
        painter.drawLine(0,0,2,2)
        self._brush = QtGui.QBrush(image)
        self._image = image

    def paintEvent(self, event):
        
        painter = QtGui.QPainter(self)
        painter.save()
        painter.setPen(QtCore.Qt.NoPen)
        painter.setBrush(self._brush)
        painter.setRenderHint(QtGui.QPainter.Antialiasing, False)
        painter.drawRect(self.rect())
        painter.restore()
        super().paintEvent(event)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    palette = app.palette()
    palette.setColor(QtGui.QPalette.Foreground, QtGui.QColor(QtCore.Qt.blue))

    label1 = LabelStandardPattern("Standard Pattern")
    label1.setPalette(palette)
    label1.setFont(QtGui.QFont("Arial", 20))
    
    label2 = LabelUserPattern("User Pattern")
    label2.setPalette(palette)
    label2.setFont(QtGui.QFont("Arial", 20))
    
    widget = QtWidgets.QWidget()
    layout = QtWidgets.QVBoxLayout()
    layout.addWidget(label1)
    layout.addWidget(label2)
    widget.setLayout(layout)
    widget.show()

    app.exec()