I'm writing a GUI application in Python, which uses multiple .py scripts. I have a variable in the QMainWindow, which I need to refer to/access in other classes. I don't have a problem importing the various .py modules into the Ui_MainWindow.py module, but I cannot seem to access the QMainWindow class variables.
This is a quick pseudo-code of what I'm trying:
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.lineEditScanBarcode.returnPressed.connect(self.LoginAttempt)
def LoginAttempt(self):
self.user_barcode = self.lineEditScanBarcode.text()
From the reading I've done on this referring to class variables, I've come to the conclusion that with the above setup, I should be able to refer to the 'user_barcode' variable in other classes as follows:
class Receipt(QWidget, Ui_Receipt):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setupUi(self)
print(MainWindow.user_barcode)
I've been using the 'print' command just to test whether it's working, but I receive the following error:
Attribute Error: type object 'MainWindow' has no attribute 'user_barcode'
Can anyone see the error I'm obviously making? I've searched SO for similar queries, but haven't found anything relevant.
Thanks!
EDIT:
Here's the app.exec_() setup, I'm not sure if I'm passing the parent correctly.
if __name__ == '__main__':
app = QApplication(sys.argv)
showMainWindow = MainWindow()
showReceipt = Receipt(MainWindow)
showMainWindow.show()
app.exec_()
I've tried various combinations, but I'm either receiving the init error, or the raised TypeError.
The reason the example code doesn't work, is because MainWindow is a class , whereas user_barcode is an attribute of an instance of that class.
For a Receipt to access the user_barcode attribute, it must somehow have the MainWindow instance made available to it. And one way to do that, is to set a MainWindow as the Receipt's parent.
This will then allow the Receipt to use the parent method to access the MainWindow instance and its attributes. Of course, this means a Receipt must always have a MainWindow as it's parent, so its constructor should probably look more like this:
class Receipt(QWidget, Ui_Receipt):
def __init__(self, parent):
if not isinstance(parent, MainWindow):
raise TypeError('parent must be a MainWindow')
super(Receipt, self).__init__(parent)
self.setupUi(self)
...
print(self.parent().user_barcode)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.