PyQT5之多页面切换

from PyQt5.QtWidgets import QApplication, QWidget, QStackedLayout, QVBoxLayout
from PyQt5.QtWidgets import QPushButton, QComboBox, QSizePolicy
import sys


if __name__ == '__main__':
  app = QApplication(sys.argv)

  my_widget = QWidget()
  my_widget_1 = QWidget(my_widget)
  my_widget_2 = QWidget()

  # 容器my_widget_1使用QVBoxLayout布局,布局中包含2个button
  my_page1_btn1 = QPushButton('A')
  my_page1_btn2 = QPushButton('B')

  # page1中将2个button加入QVBoxLayout布局
  my_page1_vbox_layout = QVBoxLayout()
  my_page1_vbox_layout.addWidget(my_page1_btn1)
  my_page1_vbox_layout.addWidget(my_page1_btn2)
  my_widget_1.setLayout(my_page1_vbox_layout)

  # 容器my_widget_2也使用QVBoxLayout布局,布局中包含2个button
  my_page2_btn1 = QPushButton('C')
  my_page2_btn2 = QPushButton('D')

  # page2中将2个button加入QVBoxLayout布局
  my_page2_vbox_layout = QVBoxLayout()
  my_page2_vbox_layout.addWidget(my_page2_btn1)
  my_page2_vbox_layout.addWidget(my_page2_btn2)
  my_widget_2.setLayout(my_page2_vbox_layout)

  # 将两个页面加入到QStackedLayout中
  my_stacked_layout = QStackedLayout()
  my_stacked_layout.addWidget(my_widget_1)
  my_stacked_layout.addWidget(my_widget_2)

  # 定义一个combobox用于选择分页
  my_combo_box = QComboBox()
  my_combo_box.addItem('页面1')
  my_combo_box.addItem('页面2')
  my_combo_box.setMinimumWidth(100)
  my_combo_box.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)

  # 顶层窗口上,使用QVBoxLayout布局,进行展示
  my_page_vbox_layout = QVBoxLayout()
  my_page_vbox_layout.addWidget(my_combo_box)
  my_page_vbox_layout.addLayout(my_stacked_layout)
  my_widget.setLayout(my_page_vbox_layout)

  # 关联信号和槽以实现多页面切换(关键步骤)
  my_combo_box.activated[int].connect(my_stacked_layout.setCurrentIndex)

  my_widget.show()

  sys.exit(app.exec_())


posted @ 2024-06-13 09:23  星空28  阅读(74)  评论(0编辑  收藏  举报