简体   繁体   中英

python - call class variable from another class

I'm working out classes and trying to get to work setCentralWidget() in my PySide GUI. I've got a MainWindow, and two widgets: mainWidget and searchWidget, which one I want to show up after the searchButton is clicked.

class MainWindow(QMainWindow):

    def __init__(self):

        super(MainWindow,self).__init__()        
        self.initUI()

    def initUI(self):

        mainWidget = MainWidget()

        self.resize(300,500)
        self.statusBar()
        self.statusBar().showMessage('Elo Elo')
        self.setCentralWidget(mainWidget)   # <---- setting centralWidget first time
        self.setWindowTitle('StartApp Welcome')

and the searchWidget()

class SearchWidget(QWidget):

    def __init__(self, parent=MainWindow):

        super(SearchWidget,self).__init__()
        self.initUI()

    def initUI(self):       

        backButton = QPushButton('GoBack', self)
        backButton.clicked.connect(self.goBack)

    def goBack(self):

        self.parent().setCentralWidget(self.parent().mainWidget)  # <--- error line

error

AttributeError: 'MainWindow' object has no attribute 'mainWidget'

I can't figure out, how to get to the MainWidget() instance 'mainWidget'. Could You help me somehow? Thanks

This is because in this line:

self.parent().setCentralWidget(self.parent().mainWidget)

you attempt to access the variable mainWidget as if it were an attribute of MainWindow - it is not (at the moment it is just a local variable). This is because you do not initialize it as self.mainWidget , which you must do to get it to work like you want it to.

self.mainwidget = MainWidget()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM