I'm learning to use PyQt5 and have run across a problem. My code is attempting to just draw a simple black box in the QMainWindow object by writing a second class PaintWidget which inherits from QWidget. I've posted my code first, and the correct one below it.
class PaintWidget(QWidget):
def __init__(self):
super().__init__()
self.qp = QPainter()
self.initUI()
def initUI(self):
self.qp.fillRect(1,1,100,100, Qt.black)
Correct:
class PaintWidget(QWidget):
def paintEvent(self, event):
qp = QPainter(self)
qp.fillRect(1, 1, 100, 100, Qt.black)
This is what confuses me. In order to create this class, we need to inherint from the super class QWidget, inorder to do so we use the function super().__init__() under __init__(self). We then set up the QPaint object which we will use in our method initUI() which actually does the work. Now this doesn't work when I run it.
The second, correct class, doesn't even seem to inherent, since it has no super().__init__(), even worse, it is setting up a method that is never even called (paintevent(self, event)), which takes an argument that seemingly comes from nowhere. Can someone point out why I'm wrong?
paintEventis called by PyQt5 with an argument it provides, and if you don’t override__init__, it defaults to the parent class’s, put simply.__init__is not needed? The reason I wanted to make one is that I thought it would make passing extra parameters to it easier, such as if I waned to change to color of the rectangle, it'd be easier to callpainter = PaintWidget(Qt.yellow).__init__is only needed if you want to initialize anything in it. Otherwise, the runtime will simply call the parent (super().__init__()) directly. However, if you want constructor parameters, go ahead and add it. It is not a problem either way. The difference is where you call the painter.