从另一个类调用函数不能正常工作

时间:2014-03-26 06:11:31

标签: python events filter pyqt

this example

帮助我理解事件是如何运作的。

但我有另一个问题。在我想要调用主类的函数的事件之后,它似乎是从Filter类开始的,不幸的是我无法从Designer-made文件中获取内容。

class Filter(QtCore.QObject):
    def eventFilter(self, widget, event):
        if event.type() == QtCore.QEvent.FocusOut:
            print 'focus out'
            print widget.objectName()
            if widget.objectName() == 'edit_notes':
                StartQT4().object_edit_notes('edit_notes')
            return False
        else:
            return False

class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self._filter = Filter()
        self.ui.edit_notes.installEventFilter(self._filter)

    def object_edit_notes(self, w):

        self.__init__()
        something = self.ui.edit_notes.toPlainText()
        something = unicode(something).encode('utf-8')
        print something
        return False

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = StartQT4()
    myapp.show()
    sys.exit(app.exec_())

属性.something不打印任何内容。我试图用信号方法button clicked()调用相同的函数,它工作正常。

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

event-filter您不需要单独的课程。继承QObjectQWidget的任何对象都会执行,其中包括QMainWindow

将事件过滤器移到您的StartQT4类中,如下所示:

class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # filter the events through self
        self.ui.edit_notes.installEventFilter(self)

    def object_edit_notes(self, w):
        # this will convert a QString to a python unicode object
        something = unicode(self.ui.edit_notes.toPlainText())
        print something

    def eventFilter(self, widget, event):
        if (event.type() == QtCore.QEvent.FocusOut and
            widget is self.ui.edit_notes):
            print 'focus out'
            self.object_edit_notes('edit_notes')
            return False
        return QMainWindow.eventFilter(self, widget, event)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = StartQT4()
    myapp.show()
    sys.exit(app.exec_())