I'm new to Python and Qt, and I have the following problem:
I have rewritten the event handler of class mywin(QMainWindow):
, so that when I click on it, a command should execute. Howewer, when the command returns an error, I would like to show an error message using QErrorMessage
. Howewer, when I click on the OK button of the Error Message, an other click event is registred and the command reexecutes, errors and shows a new error message, so I can't ever quit the error messages (Everytime I close on, an other one reopens).
def eventFilter(self, source, event):
if event.type() == QEvent.MouseButtonPress:
if isinstance(source, QWidget):
pos=event.pos()
cursor=self.txtEditor.cursorForPosition(pos)
cursor.select(QTextCursor.WordUnderCursor)
txtClicked=cursor.selectedText()
self.testCommand(str(txtClicked))
return QMainWindow.eventFilter(self, source, event)
def testCommand(self, textClicked=None):
#Command executing and error finding
if error:
errorMessage=QErrorMessage(self)
errorMessage.showMessage(a)
EDIT:
Here's the registring of the eventFilter
if __name__ == '__main__':
app = QApplication(sys.argv)
print "OS Name:"+os.name
main = mywin()
main.show()
app.installEventFilter(main)
sys.exit(app.exec_())
If I log
- the source on a click on the text region, I get:
<PyQT4.QtGui.QWidget object at 0x000000000028B30D0>
- self.textEdit, I get
<PyQT4.QtGui.QTextEdit object at 0x000000000028B3268>
Doc of installEventFilter: http://harmattan-dev.nokia.com/docs/platform-api-reference/xml/daily-docs/libqt4/qobject.html#installEventFilter
First of all you should show the code where you are registering event filter.
Secondly way you are verifying that this is the event you what to filter is not so good. You should verify specific widget not the type, so it should be something like:
def eventFilter(self, source, event):
if event.type() == QEvent.MouseButtonPress:
if source == self.txtEditor :
pos=event.pos()
cursor=self.txtEditor.cursorForPosition(pos)
cursor.select(QTextCursor.WordUnderCursor)
txtClicked=cursor.selectedText()
self.testCommand(str(txtClicked))
return QMainWindow.eventFilter(self, source, event)
Edit:
It is as I suspected: You are caching ALL events for ALL widgets since you have installed event filter on QApplication object. Register event filter on widget you what to track mouse events for. In event filter use use condition as I wrote above.
Shouldn't source
argument be different for click events coming from mywin
and QErrorMessage
objects? If yes, you could check for it and prevent the reexecution.
来源:https://stackoverflow.com/questions/17469019/pyqt-event-handling-and-qerrormessage-detect-the-source-of-the-click