How to QPainter inside QLabel

前端 未结 1 356
半阙折子戏
半阙折子戏 2021-01-23 08:02

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 Py         


        
相关标签:
1条回答
  • 2021-01-23 08:19

    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_())
    
    0 讨论(0)
提交回复
热议问题