代码之家  ›  专栏  ›  技术社区  ›  SergioSalinas

Pyqt5中的installEventFilter

  •  1
  • SergioSalinas  · 技术社区  · 7 年前

    我试图在Pyqt5中实现一个事件,但出现以下错误:

    TypeError: installEventFilter(self, QObject): argument 1 has unexpected type 'MainWindow_EXEC'
    

    这是我的密码

    import sys
    from time import sleep
    from PyQt5 import QtCore, QtWidgets
    from view_cortes2 import Ui_cortes2enter
    
    class MainWindow_EXEC():
    def __init__(self):
        app = QtWidgets.QApplication(sys.argv)
        cortes2 = QtWidgets.QMainWindow()
        self.ui = Ui_cortes2()
        self.ui.setupUi(cortes2)
        self.flag = 0
        self.ui.ledit_corteA.installEventFilter(self)
        self.ui.ledit_corteB.installEventFilter(self)
        self.ui.buttonGroup.buttonClicked.connect(self.handleButtons)
        cortes2.show()
        sys.exit(app.exec_())
    
    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.FocusIn and source is self.ui.ledit_corteA):
            print("A")
            self.flag = 0
        if (event.type() == QtCore.QEvent.FocusIn and source is self.ui.ledit_corteA):
            print("B")
            self.flag = 1
        return super(cortes2, self).eventFilter(source, event)
    
    if __name__ == "__main__":
        MainWindow_EXEC()
    

    我试图添加的事件是,当我在textedit中聚焦时,它会更改标志的值。如果我改变

    self.ui.ledit_corteA.installEventFilter(self)
    

    通过

    self.ui.ledit_corteA.installEventFilter(cortes2)
    

    我工作,但从不改变国旗的价值。

    请帮忙。

    1 回复  |  直到 6 年前
        1
  •  7
  •   eyllanesc Yonghwan Shin    7 年前

    installEventFilter 期望A QObject ,在你的情况下 MainWindow_EXEC 不是。

    如果您使用的是qt设计器设计,建议创建一个继承自相应小部件的新类,并使用qt设计器提供的类填充该类,如下所示:

    import sys
    from PyQt5 import QtCore, QtWidgets
    from view_cortes2 import Ui_cortes2
    
    class MainWindow(QtWidgets.QMainWindow, Ui_cortes2):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self.setupUi(self)
            self.flag = 0
            self.ledit_corteA.installEventFilter(self)
            self.ledit_corteB.installEventFilter(self)
            #self.buttonGroup.buttonClicked.connect(self.handleButtons)
    
        def eventFilter(self, source, event):
            if event.type() == QtCore.QEvent.FocusIn and source is self.ledit_corteA:
                print("A")
                self.flag = 0
            if event.type() == QtCore.QEvent.FocusIn and source is self.ledit_corteB:
                print("B")
                self.flag = 1
            return super(MainWindow, self).eventFilter(source, event)
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec_())
    

    参考文献: