【问题标题】:Calling function from another class doesn't work properly从另一个类调用函数不能正常工作
【发布时间】:2014-05-04 08:58:32
【问题描述】:

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() 调用相同的函数,它工作正常。

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

【问题讨论】:

    标签: python events filter pyqt


    【解决方案1】:

    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_())
    

    【讨论】:

      猜你喜欢
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      相关资源
      最近更新 更多