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

2024-04-26 20:42:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将一个字符串变量从Main_Window类传递给PyQt中的另一个QDialog类。我不明白我做错了什么。我想把host_mac变量从主类传递到QDialog类。这里是我代码的主要部分。在

以下是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

这里是主窗口类:

^{pr2}$

但我得到了以下错误:

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

Tags: selfclienthostinitismainmacdef
1条回答
网友
1楼 · 发布于 2024-04-26 20:42:12

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
        ...

使用方式如下:

^{pr2}$

另外,您可能需要使用新样式的连接语法:

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

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

相关问题 更多 >