Skip to main content
 首页 » 编程设计

python之Pyside QWidgetList 项目分配多个图标

2024年09月07日27yyy_WW

我知道如何将 1 个图标分配给 QWidgetList 中的项目。是否可以分配超过 1 个图标?就像我附上的图片一样,我想向“a”添加第二个图标(绿色图标)并能够在特定条件下将其删除。下面的代码只是我想要实现的一个例子

from PySide2.QtCore import * 
from PySide2.QtGui import * 
from PySide2.QtWidgets import * 
 
class MainWindow(QWidget): 
    def __init__(self): 
        QWidget.__init__(self) 
 
        self.orange = QIcon('orangeIconPath') 
        self.green = QIcon('greenIconPath') 
        self.layout=QVBoxLayout() 
        self.setLayout(self.layout) 
 
        self.widget1=QWidget() 
        self.layout.addWidget(self.widget1) 
 
        self.layout1=QVBoxLayout() 
        self.widget1.setLayout(self.layout1) 
 
        self.layout1.addWidget(QLabel("First layout")) 
        self.qlist = QListWidget() 
        self.layout1.addWidget(self.qlist) 
 
        items = ['a','b','c'] 
        self.qlist.addItems(items) 
 
        #This is where I'm struggling when it's more than 1 icon 
        #enter a condition to check against each item and assign icon/s to the item when condition is met 
 
        self.show() 

请您参考如下方法:

不,不是使用QListWidget,至少不是单独使用。

不过,您有多种选择。

在这种情况下,我个人的偏好是使用QTreeWidget。 QTreeWidget 的行为非常类似于具有多列的 QListWidget,因此您可以在这些列中放置图标。你需要摆弄它一些来配置列宽,如果你不想在那里,可能会删除标题栏,但这并不是特别困难(如果需要,我很乐意提供额外的建议) .您也可以使用 QTableWidget 来达到同样的目的,但需要更多的配置才能使其表现得像一个列表。

另一种选择是以编程方式生成具有多个并排图标的新图标,因此您只需设置一个图像。

显着更高级的是 create a delegate对于 View 。我不会在这里详细介绍这一点,因为它需要大量工作,但它也为您提供了最大的控制权。


作为旁注,我建议不要使用 QListWidget /QTreeWidget/QTableWidget View 类。它们真的很容易上手,没错,但是熟悉使用模型 View QListView/QTreeView/QTableView 确实值得类。编写您自己的 QAbstractListModel 或 QAbstractTableModel 子类非常容易,或者您可以使用 QStringListModel 简单列表和 QStandardItemModel 作为两种类型的 View 类之间的垫脚石。