センターウィジェットの入れ替え

2016/08/15

Python2.7.10, PySide1.2.2

from PySide import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.central_widget = QtGui.QStackedWidget()
        self.setCentralWidget(self.central_widget)
        self.widget1 = Widget1(self)
        self.widget2 = Widget2(self)

        self.widget1.button.clicked.connect(self.switch)
        self.widget2.button.clicked.connect(self.switch)

        self.central_widget.addWidget(self.widget1)
        self.central_widget.addWidget(self.widget2)
        self.central_widget.setCurrentWidget(self.widget1)

        self.widget_no = 1

    def switch(self):
        if self.widget_no == 1:
            self.central_widget.setCurrentWidget(self.widget2)
            self.widget_no = 2
        else:
            self.central_widget.setCurrentWidget(self.widget1)
            self.widget_no =1

class Widget1(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget1, self).__init__(parent)
        layout = QtGui.QHBoxLayout()
        self.label = QtGui.QLabel('widget 1 !')
        layout.addWidget(self.label)
        self.button = QtGui.QPushButton('Switch')
        layout.addWidget(self.button)
        self.setLayout(layout)

class Widget2(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget2, self).__init__(parent)
        layout = QtGui.QHBoxLayout()
        self.label = QtGui.QLabel('widget 2 !')
        layout.addWidget(self.label)
        self.button = QtGui.QPushButton('Switch')
        layout.addWidget(self.button)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QtGui.QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()


Replace CentralWidget in MainWindow
http://stackoverflow.com/questions/13550076/replace-centralwidget-in-mainwindow