How to QPainter inside QLabel

2020-04-20 12:24发布

问题:

I can not understand how to make the QPainter() draw inside a QLabel, here is the code I told would have worked:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPainter, QColor, QBrush

class Labella(QLabel):

    def __init__(self, parent):
        super().__init__()

        lb = QLabel('text', parent)
        lb.setStyleSheet('QFrame {background-color:grey;}')
        lb.resize(200, 200)

        qp = QPainter(lb)
        qp.begin(lb);

        qp.setBrush(QColor(200, 0, 0))
        qp.drawRect(0,0,20,20);
        qp.end();


    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        self.drawRectangles(qp)
        qp.end()

    def drawRectangles(self, qp):

        col = QColor(0, 0, 0)
        col.setNamedColor('#040404')
        qp.setPen(col)

        qp.setBrush(QColor(200, 0, 0))
        qp.drawRect(10, 15, 200, 60)


class Example(QWidget):

    def __init__(self):
        super().__init__()

        lb = Labella(self)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Colours')
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

I can only find examples in C++ same as for the Qt documentation, please instruct me where I should have find the information if not here.

回答1:

The documentation suggests to use QPainter inside the paintEvent.

By using the constructor like below, inside the method paintEvent, no need to call begin() and end()

(Your class Labella just miss a parameter to initialize the parent)

The method save() and restore() can be convenient to store a standard config of a QPainter, allowing to draw something different before restoring the settings.

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPainter, QColor, QBrush

class Labella(QLabel):

    def __init__(self, parent):
        super().__init__(parent=parent)

        self.setStyleSheet('QFrame {background-color:grey;}')
        self.resize(200, 200)

    def paintEvent(self, e):
        qp = QPainter(self)
        self.drawRectangles(qp)
        qp.setBrush(QColor(200, 0, 0))
        qp.drawRect(0,0,20,20)

    def drawRectangles(self, qp):    
        qp.setBrush(QColor(255, 0, 0, 100))
        qp.save() # save the QPainter config

        qp.drawRect(10, 15, 20, 20)

        qp.setBrush(QColor(0, 0, 255, 100))
        qp.drawRect(50, 15, 20, 20)

        qp.restore() # restore the QPainter config            
        qp.drawRect(100, 15, 20, 20)

class Example(QWidget):

    def __init__(self):
        super().__init__()

        lb = Labella(self)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Colours')
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())