Search code examples
pythonqtpyqtpysideqpainter

My paintEvent method is not painting anything with PySide


I'm trying to draw a circle on top of a label (which has a background image of a circuit board) to represent an output pin's state.

I'm just trying to draw something at the moment but I'm not getting anything drawn.

Here is my (shortened) class:

class MyClass(QMainWindow, Ui_myGeneratedClassFromQtDesigner):
    def paintEvent(self, event):                                                                                                                     
        super(QMainWindow, self).paintEvent(event)                             
        print("paint event")
        painter = QtGui.QPainter()
        painter.begin(self)
        painter.drawElipse(10, 10, 5, 5)
        painter.end()

paint event is printed to the console but there is nothing drawn in the window. Am I using QPainter correctly?


Solution

  • There's only a syntax error in your code, see how this example works:

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    
    from PyQt4 import QtGui, QtCore
    
    class MyWindow(QtGui.QLabel):
        def __init__(self, parent=None):
            super(MyWindow, self).__init__(parent)
    
        def animate(self):
            animation = QtCore.QPropertyAnimation(self, "size", self)
            animation.setDuration(3333)
            animation.setStartValue(QtCore.QSize(self.width(), self.height()))
            animation.setEndValue(QtCore.QSize(333, 333))
            animation.start()
    
        def paintEvent(self, event):
            painter = QtGui.QPainter(self)
            painter.setBrush(QtGui.QBrush(QtCore.Qt.red))
            painter.drawEllipse(0, 0, self.width() - 1, self.height() - 1)
            painter.end()
    
        def sizeHint(self):
            return QtCore.QSize(111, 111)
    
    if __name__ == "__main__":
        import sys
    
        app = QtGui.QApplication(sys.argv)
        app.setApplicationName('MyWindow')
    
        main = MyWindow()
        main.show()
        main.animate()
    
        sys.exit(app.exec_())