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.
The documentation suggests to use
QPainterinside thepaintEvent.By using the constructor like below, inside the method
paintEvent, no need to callbegin()andend()(Your class Labella just miss a parameter to initialize the parent)
The method
save()andrestore()can be convenient to store a standard config of a QPainter, allowing to draw something different before restoring the settings.