Search code examples
pythonpython-3.xpyqtpyqt4paintevent

PaintEvent triggered couple times my code


I dont understand why PaintEvent perfoming my code three and more time... Why and where it's initianilised so many times? Is it real repainting so many times and why?

def dispTabs(self):         
    self.w = MyPopup1()
    self.ui.tabWidget.addTab(self.w, 'Test')


class MyPopup1(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self)   
        print 'ok'

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

    def drawRectangles(self, qp):
        print 'ok 2'
        color = QtGui.QColor(0, 0, 0)
        color.setNamedColor('#d4d4d4')
        qp.setPen(color)

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

Output:

ok
ok2
ok2
ok2

Later may added more 'ok2'...


Solution

  • The paintEvent method is called every time the GUI is required to be repainted, and this is called many times for example when you first display the widget, when you move the widget, when you hover your mouse over the widget, etc. The XEvent methods should not be called directly but are invoked by events handled by Qt, that is, Qt decides when it needs to be called, in this case Qt analyzes when it is necessary to repaint.