我知道如何将 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为了景观。我不会在这里详细介绍这一点,因为这需要大量工作,但它也为您提供了最大的控制权。
作为旁注,我建议不要使用QListWidget
/QTreeWidget
/QTableWidget
View 类。它们确实很容易上手,确实如此,但确实值得您熟悉使用模型 View QListView
/QTreeView
/QTableView
类。编写自己的 QAbstractListModel
或 QAbstractTableModel
子类非常容易,或者您可以使用 QStringListModel
来实现简单列表和 QStandardItemModel
code> 作为两种类型的 View 类之间的垫脚石。
关于python - Pyside QWidgetList 项目分配多个图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49081290/