在PyQt中将变量从一个类传递到另一个类

时间:2015-08-05 21:35:40

标签: python python-2.7 pyqt pyqt4

我想将一个字符串变量从Main_Window类传递给PyQt中的另一个QDialog类。我无法理解我做错了什么。我想将host_mac变量从Main Class传递给QDialog Class。这是我的代码的主要部分。

这是QDialog类:

class Client(QDialog):
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)
        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.set_client)
        self.setWindowTitle("Learning")

    def set_client(self):
        self.client = self.le.text()
        print 'provided client mac is ' + self.client + 'and host_mac is ' + Main_window_ex.host_mac

这里是Main_Window类:

class Main_window_ex(QMainWindow, Ui_Main_window):   
    def __init__(self, parent = None):
    """
    Default Constructor. It can receive a top window as parent. 
    """
    QMainWindow.__init__(self, parent)
    self.setupUi(self)


    self.host_mac = 'blah blah'

#more code beneeth

但是我收到以下错误:

AttributeError: type object 'Main_window_ex' has no attribute 'host_mac'

1 个答案:

答案 0 :(得分:2)

Main_window_ex.host_mac指的是变量(因为Main_window_ex只是一个类),但您想要访问实例变量。换句话说,在实例化类之前,不会定义host_mac

有几种方法可以解决这个问题。假设Main_window_ex负责创建Client,那么一种简单的方法是将变量传递给Client

class Client(QDialog):
    def __init__(self, host_mac, parent=None):
        self.host_mac = host_mac
        ...

并使用它:

    def set_client(self):
        self.client = self.le.text()
        print 'provided client mac is ' + self.client + 'and host_mac is ' + self.host_mac

作为旁注,您可能希望使用新的样式连接语法:

# old style
# self.connect(self.pb, SIGNAL("clicked()"),self.set_client)

# new style
self.pb.clicked.connect(self.set_client)