PySide6 GUI 编程(19):QStackedWidget的简单用法

2024-07-30 09:39:18 浏览数 (1)

示例代码

代码语言:python代码运行次数:0复制
import random

from PySide6.QtCore import Qt
from PySide6.QtGui import QColor, QFont, QPalette
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow, QPushButton, QStackedWidget, QVBoxLayout, QWidget


class ColorWidget(QWidget):
    def __init__(self, color: QColor, content: str):
        super().__init__()
        label = QLabel(content)
        label.setAutoFillBackground(True)
        palette = label.palette()
        palette.setColor(QPalette.ColorGroup.Normal, QPalette.ColorRole.Window, color)
        label.setPalette(palette)
        label.setAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter)
        label.setFont(QFont('Arial', 40))
        layout = QVBoxLayout()
        layout.addWidget(label)
        self.setLayout(layout)


class MyStackedWidgets(QMainWindow):
    def __init__(self, tabs_num: int = 5):
        super().__init__()
        self.default_tabs_num = 5
        # 获取原始的列表
        color_names = QColor.colorNames()
        # 随机洗牌打乱顺序
        random.shuffle(color_names)
        # 获取总数
        self.max_tabs_num = len(color_names)
        if tabs_num <= 0 or tabs_num >= self.max_tabs_num:
            print(f'invalid tabs_num: {tabs_num}, reset to default value: {self.default_tabs_num}')
            self.tabs_num = self.default_tabs_num
        else:
            self.tabs_num = tabs_num
        self.stacked_widget = QStackedWidget()
        for i in range(0, self.tabs_num):
            color_ins = ColorWidget(QColor(color_names[i]), color_names[i])
            self.stacked_widget.addWidget(color_ins)
        self.current_index = 0  # 默认设置为 0
        self.button = QPushButton(f'Next Tab, Total Tabs: {self.tabs_num}, Current Tab Index: {self.current_index}')
        self.button.clicked.connect(self.next_tab)

        layout_v = QVBoxLayout()
        layout_v.addWidget(self.button)
        layout_v.addWidget(self.stacked_widget)
        container = QWidget()
        container.setLayout(layout_v)
        self.setCentralWidget(container)

    def next_tab(self):
        self.current_index  = 1
        self.stacked_widget.setCurrentIndex(self.current_index % self.tabs_num)
        self.button.setText(
            f'Next Tab, Total Tabs: {self.tabs_num}, '
            f'Current Tab Index: {(self.current_index % self.tabs_num)}')


if __name__ == '__main__':
    app = QApplication()
    ins = MyStackedWidgets()
    ins.show()
    app.exec()

运行效果

静态效果静态效果
交互效果交互效果

0 人点赞