I want to pass a string variable from Main_Window
class to another QDialog
class in PyQt. I can't understand what I do wrong. I want to pass host_mac
variable from Main Class to QDialog Class. Here the main part of my code.
Here is the QDialog class:
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
And here the Main_Window Class:
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
But I get the following error:
AttributeError: type object 'Main_window_ex' has no attribute 'host_mac'
Main_window_ex.host_mac
refers to a class variable (as Main_window_ex
is only a class), but you are wanting to access the instance variable. In other words, host_mac
is not defined until the class is instantiated.
There are a few ways around this. Assuming Main_window_ex
is responsible for creating Client
, then one simple way is to pass the variable to Client
:
class Client(QDialog):
def __init__(self, host_mac, parent=None):
self.host_mac = host_mac
...
And use it like:
def set_client(self):
self.client = self.le.text()
print 'provided client mac is ' + self.client + 'and host_mac is ' + self.host_mac
As a side note you may want to use the new style connection syntax:
# old style
# self.connect(self.pb, SIGNAL("clicked()"),self.set_client)
# new style
self.pb.clicked.connect(self.set_client)