0

In this program below, I am testing the affect of mousePressEvent:

import sys
from PyQt4 import QtGui, Qt, QtCore


class Test(QtGui.QFrame):
    def __init__(self):
        QtGui.QFrame.__init__(self)
        self.setGeometry(30,30,500, 500)
        self.show()

    def paintEvent(self, e=None): 
        print "paintEvent"
        qp = QtGui.QPainter()
        qp.begin(self)
        qp.drawRect(30,30,80,80)
        qp.end()

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.RightButton:
            print "mousePressEvent- Right"
        else:
            print "mousePressEvent- Left"

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Test()
    sys.exit(app.exec_())

I see that in the first left-click, the frame's paintEvent is called. Is this because when the frame get the focus, it need to be repainted? I wonder if there is any way to avoid paintEvent to be called and every drawing in the frame still intact. The reason is because in my real program, the paintEvent is really heavy, I want to run it as less times as possible.

If that is not possible, is there a way to avoid the frame getting focus when left-click on that?

HuongOrchid
  • 332
  • 3
  • 15
  • Yes, the paint can happen when the focus changes (and not for the actual clicks). The obvious thing would be to have a scene_was_changed flag that says whether a redraw is actually needed or not. To actually change the calling of paintEvent, you could intercept the focusIn and focusOut events. – mdurant Sep 25 '14 at 19:22
  • If you want to reject event then you can use event.ignore() – Achayan Sep 25 '14 at 20:04

1 Answers1

0

I don't know whether there are platform-specific differences at play here, but when I try the example code on Linux, there is no paintEvent when clicking on the frame.

This is not surprising really, because, by default, the QFrame is not configured to accept focus of any kind. To get the example to work, I had to explicitly set the focus policy, like this:

class Test(QtGui.QFrame):
    def __init__(self):
        QtGui.QFrame.__init__(self)
        self.setFocusPolicy(QtCore.Qt.StrongFocus)

But maybe the defaults are somehow different on other platforms, and so, to explicitly prevent the frame getting the focus, you might need to do this:

        self.setFocusPolicy(QtCore.Qt.NoFocus)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336