pythonpyside2qmainwindowqstatusbar

How to access QstatusBar in QMainWindows from a widget class?


I'm trying to change the text of a Qstatusbar created in a mainwindows Class from another class

I've try several thing for the web but didn't find the answer ...

class MainWindow(QMainWindow):

    def __init__(self, widget):
        QMainWindow.__init__(self)
        self.setWindowTitle("Main Windows")

        # Status Bar
        self.main_statusbar = QStatusBar()
        self.main_statusbar.showMessage("Ready")
        self.setStatusBar(self.main_statusbar)

class Widget(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        self.buttons_layout = QHBoxLayout()
        self.btn_enregister = QPushButton("Save")
        self.btn_enregister.clicked.connect(self.save_information)

    def save_information(self):

        if self.line_prenom.text() and self.line_nom.text():
            info_client.write(db)
        else:
            (this line)---> main_statusbar.showMessage("Fidouda")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = Widget()
    window = MainWindow(widget)
    window.resize(800, 700)
    window.show()
    sys.exit(app.exec_())

I would like to be able to modify the statusbar text created in the MainWindow class from the Widget class


Solution

  • One of the advantages of Qt over other libraries are the signals that allow you to notify between objects, in this case it is the best option:

    from PySide2.QtCore import Signal # <---
    
    
    class MainWindow(QMainWindow):
    
        def __init__(self, widget):
            QMainWindow.__init__(self)
            self.setWindowTitle("Main Windows")
    
            # Status Bar
            self.main_statusbar = QStatusBar()
            self.main_statusbar.showMessage("Ready")
            self.setStatusBar(self.main_statusbar)
            widget.messageChanged.connect(self.main_statusbar.showMessage) # <---
    
    class Widget(QWidget):
        messageChanged = Signal(str) # <---
    
        # ...
    
        def save_information(self):
    
            if self.line_prenom.text() and self.line_nom.text():
                info_client.write(db)
            else:
                self.messageChanged.emit("Fidouda") # <---