赞
踩
QStackedWidget是一个堆栈窗口控件,用于管理多个堆叠的子部件。它只显示当前选中的子部件,而隐藏其余的子部件。
例子:
ControlWidget窗口中,创建QStackedWidget,分别添加两个组件,为Test1Widget和Test2Widget,两个组件都添加ViewOnButton,通过ViewOnButton切换两个组件。
from PyQt5.QtWidgets import * import sys class ViewOnButton(QPushButton): def __init__(self, is_view=True): super().__init__() self.is_view = is_view self.init_ui() def init_ui(self): self.setMaximumWidth(100) if self.is_view: self.setText(" 画面1") font_color = "rgb(70, 106, 170)" else: self.setText(" 画面2") font_color = "rgb(231, 197, 111)" style_str = """QPushButton {{background-color: rgb(240, 254, 230); border-style: outset; border-width: 2px; border-color: #8f8f91; border-radius: 6px; padding: 6px; font-size: 16px; font-weight: bold; color: {};}}""".format(font_color) self.setStyleSheet(style_str) class Test1Widget(QWidget): """ 动态视图页面 """ def __init__(self): super(Test1Widget, self).__init__() self.main_layout = QVBoxLayout() self.main_layout.setContentsMargins(10, 10, 10, 10) self.setStyleSheet("background-color: blue;") self.setLayout(self.main_layout) self.label = QLabel("我是组件1画面") h_layout = QHBoxLayout() h_layout.addStretch(1) self.preview_btn = ViewOnButton(is_view=False) h_layout.addWidget(self.preview_btn) self.main_layout.addLayout(h_layout) self.main_layout.addWidget(self.label) def get_btn(self): return self.preview_btn class Test2Widget(QWidget): """ 动态视图页面 """ def __init__(self): super(Test2Widget, self).__init__() self.main_layout = QVBoxLayout() self.main_layout.setContentsMargins(10, 10, 10, 10) self.setStyleSheet("background-color: yellow;") self.setLayout(self.main_layout) self.label = QLabel("我是组件2画面") h_layout = QHBoxLayout() h_layout.addStretch(1) self.view_btn = ViewOnButton(is_view=True) h_layout.addWidget(self.view_btn) self.main_layout.addLayout(h_layout) self.main_layout.addWidget(self.label) def get_btn(self): return self.view_btn class ControlWidget(QWidget): """ 控制主页面 """ def __init__(self): super(ControlWidget, self).__init__() self.resize(400, 200) self.setWindowTitle("切换页面测试") self.main_layout = QVBoxLayout() self.main_layout.setContentsMargins(10, 10, 10, 10) self.setLayout(self.main_layout) self.stacked_widget = QStackedWidget() self.main_layout.addWidget(self.stacked_widget) self.widget1 = Test2Widget() self.widget2 = Test1Widget() self.stacked_widget.addWidget(self.widget1) self.stacked_widget.addWidget(self.widget2) self.case_btn = self.widget1.get_btn() self.view_btn = self.widget2.get_btn() self.case_btn.clicked.connect(self.switch_to_view) self.view_btn.clicked.connect(self.switch_to_case) def switch_to_view(self): self.stacked_widget.setCurrentWidget(self.widget2) def switch_to_case(self): self.stacked_widget.setCurrentWidget(self.widget1) app = QApplication(sys.argv) window = ControlWidget() window.show() sys.exit(app.exec_())
结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。