QStackedWidget实例
#!/usr/bin/python # _*_ Coding: Utf-8 _*_ ''' QStackedWidget useful properties and methods of qtabwidget funcs: addWidget(QWidget *widget), removeWidget(QWidget *widget) --- add & remove widget indexOf(QWidget *widget) --- get index of widget insertWidget(int index, QWidget *widget) --- insert widget to index count() --- return amount of widgets currentIndex() and currentWidget() --- return index and widget of current slots: setCurrentIndex(int index) setCurrentWidget(QWidget *widget) signals: currentChanged(int index) widgetRemoved(int index) --- edit by yangrui ''' import sys from PyQt5.QtCore import * from PyQt5.QtWidgets import (QApplication, QWidget, QStackedWidget, QLabel, QComboBox) from PyQt5.QtGui import * class MystackedWidget(QWidget): qss = """ #label1 { background: #545D4F; } #label2 { background: #FAA45D; } #label3 { background: #6AF45D; } #label4 { background: #2AA45D; } """ def __init__(self): super(MystackedWidget, self).__init__() self.initUI() def initUI(self): self.resize(600, 400) self.stackedWidget = QStackedWidget(self) label1 = QLabel("page 1") label1.setFixedSize(150, 60) label1.setObjectName("label1") label2 = QLabel("page 2") label2.setFixedSize(150, 60) label2.setObjectName("label2") label3 = QLabel("page 3") label3.setFixedSize(150, 60) label3.setObjectName("label3") label4 = QLabel("page 4") label4.setFixedSize(150, 60) label4.setObjectName("label4") # use combobox to change stacked widget's current index self.combobox = QComboBox(self) for i in range(4): self.combobox.addItem("Page {0}".format(i+1)) self.combobox.activated.connect(self.stackedWidget.setCurrentIndex) self.stackedWidget.addWidget(label1) self.stackedWidget.addWidget(label2) self.stackedWidget.addWidget(label3) self.stackedWidget.addWidget(label4) if __name__ == '__main__': app = QApplication(sys.argv) form = MystackedWidget() form.show() app.exec_()