我是Python和Qt的新手,有以下问题:我已经重写了class mywin(QMainWindow):
的事件处理程序,这样当我点击它时,就会执行一个命令。但是,当命令返回错误时,我希望使用QErrorMessage
显示一条错误消息。然而,当我单击错误消息的"确定"按钮时,会注册另一个单击事件,命令会重新执行、出错并显示新的错误消息,因此我永远无法退出错误消息(每次关闭时,都会重新打开另一个)。
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)
编辑:
这是eventFilter 的注册表字符串
if __name__ == '__main__':
app = QApplication(sys.argv)
print "OS Name:"+os.name
main = mywin()
main.show()
app.installEventFilter(main)
sys.exit(app.exec_())
如果我记录
- 点击文本区域的来源,我得到:
<PyQT4.QtGui.QWidget object at 0x000000000028B30D0>
- self.textEdit,我得到
<PyQT4.QtGui.QTextEdit object at 0x000000000028B3268>
installEventFilter的文档:http://harmattan-dev.nokia.com/docs/platform-api-reference/xml/daily-docs/libqt4/qobject.html#installEventFilter
首先,您应该显示注册事件过滤器的代码
第二种方法是验证这是你要过滤的事件,但效果不太好。你应该验证特定的小部件,而不是类型,所以它应该是这样的:
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)
编辑:
正如我所怀疑的:由于在QApplication对象上安装了事件过滤器,所以您正在为所有小部件缓存所有事件。在小部件上注册事件过滤器,以便跟踪鼠标事件。在事件过滤器中使用我上面写的使用条件。
mywin
和QErrorMessage
对象的点击事件,source
参数不应该不同吗?如果是,您可以检查并阻止重新执行。