Common buttons and positioning in Python PyQt5 QStackedLayout



  • I am creating a Python PyQt5 app for a university project, which uses QStackedLayout to keep the app single-windowed.

    First question: how can I create buttons that appear on every window and have the same function and property without having to recreate them in every window's UI setup (like in the code)?

    Second question: after switching windows, how can I open the newly opened window at the previous's position? Right now they just open at the centre of the screen. I assume pos() or QPoint should be used but I can not figure out how.

    The code:

    import sys
    
    from PyQt5.QtWidgets import (QApplication,
                                 QMainWindow, 
                                 QPushButton,
                                 QWidget,
                                 QStackedLayout)
    
    class Ui(QWidget):
    
        def setupUi(self, Main):
    
            self.application_width  = 200
            self.application_height = 200
    
            self.stack = QStackedLayout()
    
            self.window_1 = QWidget()        
            self.window_2 = QWidget()
    
            self.window_1_UI()
            self.window_2_UI()
    
            self.stack.addWidget(self.window_1)
            self.stack.addWidget(self.window_2)
    
        def window_1_UI(self):
    
            self.window_1.setFixedSize(self.application_width, self.application_height)       
            self.window_1.setWindowTitle("1")
    
            '''REPLACE THIS BUTTON'''
            self.window_1_button = QPushButton("Change window", self.window_1)
    
        def window_2_UI(self):
    
            self.window_2.setFixedSize(self.application_width, self.application_height)
            self.window_2.setWindowTitle("2")
    
            '''AND REPLACE THIS BUTTON'''
            self.window_2_button = QPushButton("Change window", self.window_2)
    
    class Main(QMainWindow, Ui):
    
        def __init__(self):
    
            super(Main, self).__init__()
    
            self.setupUi(self)
    
            self.window_1_button.clicked.connect(self.change_window)
            self.window_2_button.clicked.connect(self.change_window)
    
        def change_window(self):
    
            if self.stack.currentIndex() == 0:
    
                self.stack.setCurrentIndex(1)
    
            else:
    
                self.stack.setCurrentIndex(0)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        M = Main()
        sys.exit(app.exec())
    

  • Lifetime Qt Champion

    Hi,

    You can put your QStackedLayout and buttons in a QVBoxLayout so you can re-use the buttons. Put that layout in a QWidget and set that widget as the central widget of your QMainWindow.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.