簡體   English   中英

在PyQt中將變量從一個類傳遞到另一個

[英]Pass a variable from one Class to another in PyQt

我想將字符串變量從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'

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM