Python:如何在PyQt中访问已经实例化的类对象?

时间:2016-09-09 01:54:14

标签: python oop scope pyqt pyqt5

我有一个基类的简单子类QLineEdit,它只是PyQt5的一个可编辑文本框:

class pQLineEdit(QtWidgets.QLineEdit):
    def __init__(self, parent = None):
        QtWidgets.QWidget.__init__(self,parent)

    def mouseDoubleClickEvent(self,e):
        self.setText("Test")

这个课程很好。当我双击它时,对象的文本确实更新了。

但是,在这个事件中,我需要从另一个已经实例化的类访问另一个文件中的对象foo.bar。我怎样才能做到这一点?我试过了

import other_file
...
def mouseDoubleClickEvent(self,e):
  self.setText("Test")
  foo.bar

我明白了:

 NameError: global name 'foo' is not defined

我尝试使用

进行黑客攻击
eval("foo.bar") 

但它抱怨foo.bar没有定义。我觉得这很简单,但答案却没有。

我应该澄清:foo()是在另一个文件的FUNCTION中实例化的类,它是main()。我必须访问实例化的类,因为它包含SSH隧道。我不认为我的问题是列出的欺骗。

1 个答案:

答案 0 :(得分:1)

冒着明显的风险:如果你想访问一个变量,你需要把它放在可以访问的地方。该函数之外的任何代码都无法访问函数的本地范围。

要使另一个模块可以访问变量,必须在全局范围内分配该变量,或者将其指定为全局范围内另一个对象的属性。

如果在加载模块时无法分配变量,请使用//@flow class MyClass { x: number; constructor(){ this.x = 1 } } (MyClass.prototype.types: Object); MyClass.prototype.types = {}; const x : number = MyClass.prototype.types; 语句对其进行定义:

global

但是,对于gui应用程序更合适的方法是在顶级窗口中提供对变量的访问:

foo = None

def main():
    global foo
    foo = MyClass()
    ...

任何以父窗口为主窗口的子窗口小部件都可以通过class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.foo = MyClass() 方法访问变量:

parent()

<强> PS

请注意,如果您将行编辑放在布局中,它将自动重新设置为布局的父级。在class LineEdit(QtWidgets.QLineEdit): def __init__(self, parent=None): super(LineEdit, self).__init__(parent) def mouseDoubleClickEvent(self, event): bar = self.parent().foo.bar 中,这可能是中心窗口小部件。在这种情况下,您应该在central-widget上设置属性,或者使用QMainWindow检索主窗口。