【问题标题】:How to create expandable icon groups in pyqt?如何在 pyqt 中创建可扩展的图标组?
【发布时间】:2022-12-19 21:12:44
【问题描述】:

我使用 QListView 在 PyQt 中创建了一个应用程序,当双击打开相应的应用程序时,它有一堆图标。

我想将相似类别的应用程序合并为一组以减少混乱。用户可以单击该组以展开并选择他们需要的图标/应用程序。单击外部以折叠组。该组需要与其他图标/应用处于同一级别

我尝试使用 Stacked Widget 但这不是一个优雅的解决方案。我可以使用哪些小部件/技术来实现这一目标?提前致谢!

【问题讨论】:

    标签: python python-3.x user-interface pyqt pyqt5


    【解决方案1】:

    您可以使用 QTreeWidget 来实现此目的。它允许您创建具有可扩展和可折叠节点的项目的层次结构。它还允许您为每个部分添加标题,使其更易于识别和导航。

    这是一个非常小的示例以及输出:

    import sys
    from PyQt5 import QtWidgets, QtGui
    
    app = QtWidgets.QApplication(sys.argv)
    treeWidget = QtWidgets.QTreeWidget()
    
    # Create the headers
    treeWidget.setHeaderLabels(["Group", "App"])
    
    # Create the groups
    group1 = QtWidgets.QTreeWidgetItem(treeWidget, ["Office Suite"])
    group2 = QtWidgets.QTreeWidgetItem(treeWidget, ["Graphics Suite"])
    
    # Create items in the groups
    wordItem = QtWidgets.QTreeWidgetItem(group1, ["Word", "icon.png"])
    excelItem = QtWidgets.QTreeWidgetItem(group1, ["Excel", "icon.png"])
    
    illustratorItem = QtWidgets.QTreeWidgetItem(group2, ["Illustrator", "icon.png"])
    photoshopItem = QtWidgets.QTreeWidgetItem(group2, ["Photoshop", "icon.png"])
    
    # Set the icons
    wordItem.setIcon(1, QtGui.QIcon("icon.png"))
    excelItem.setIcon(1, QtGui.QIcon("icon.png"))
    illustratorItem.setIcon(1, QtGui.QIcon("icon.png"))
    photoshopItem.setIcon(1, QtGui.QIcon("icon.png"))
    
    # Expand the groups
    treeWidget.expandItem(group1)
    treeWidget.expandItem(group2)
    
    # Set the action to perform when an item is double clicked
    def itemDoubleClicked(item, column):
        if column == 1:
            print("Opening app: ", item.text(0))
    
    treeWidget.itemDoubleClicked.connect(itemDoubleClicked)
    treeWidget.show()
    sys.exit(app.exec_())
    

    这是输出的屏幕截图(没有放置图标):

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 2011-08-18
      相关资源
      最近更新 更多