QToolBox控件学习

166 阅读1分钟

PyQt快速上手书籍学习

Kapture 2025-05-10 at 14.44.08.gif

实现代码

from PyQt6.QtGui import QPixmap, QIcon
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QGroupBox, QToolBox
import sys


class MainWindows(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ui()

    def ui(self):
        self.setWindowTitle("QtoolBox学习")
        self.resize(200, 200)
        self.show()

        main_layout = QVBoxLayout()
        v_layout = QVBoxLayout()
        self.label1 = QLabel("1")
        self.label2 = QLabel("2")
        self.label3 = QLabel("3")
        v_layout.addWidget(self.label1)
        v_layout.addWidget(self.label2)
        v_layout.addWidget(self.label3)
        self.group1 = QGroupBox("数值")
        self.group1.setLayout(v_layout)

        v_layout2 = QVBoxLayout()
        self.label4 = QLabel("a")
        self.label5 = QLabel("b")
        self.label6 = QLabel("c")
        v_layout2.addWidget(self.label4)
        v_layout2.addWidget(self.label5)
        v_layout2.addWidget(self.label6)
        self.group2 = QGroupBox("字母")
        self.group2.setLayout(v_layout2)

        # main_layout.addWidget(self.group1)
        # main_layout.addWidget(self.group2)
        self.tool_box = QToolBox()
        # 设置style
        self.tool_box.setStyleSheet("""
            QToolBox {
                min-height: 100px;
            }
        """)

        self.tool_box.addItem(self.group2, "字母")
        self.tool_box.insertItem(0, self.group1, "数字")
        self.tool_box.setItemText(0, "数值")
        # 设置图标
        self.tool_box.setItemIcon(0, QIcon(
            "/Users/wangjien/PycharmProjects/pythonGit/PyQt6学习/2_书籍学习/2_2_控件/QtoolBox/字体.png"))
        self.tool_box.setItemIcon(1, QIcon(
            "/Users/wangjien/PycharmProjects/pythonGit/PyQt6学习/2_书籍学习/2_2_控件/QtoolBox/数字字典管理.png"))
        main_layout.addWidget(self.tool_box)
        self.setLayout(main_layout)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindows()
    sys.exit(app.exec())