问题
Is it possible to to set QListWidget items in groups.
For example if i am adding the content of a folder to listwidget. i want to show all folders in folders group and files in files group. Like in the image below.
Is it possible.
回答1:
Create for each group a list with all items, sort the list by an arbitrary property and add the item groups in desired order to listwidget. Between or in front of the groups a delimiter or title can be added, the groups can get different styles.
e.g. your files/folders groups:
files.sort() # list of files
folders.sort() # list of folders
for f in folders:
item = QtWidgets.QListWidgetItem()
item.setIcon(QtGui.QIcon('icon1.xpm'))
item.setText(f)
# set further properties like font, background ...
item.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
self.listWidget.addItem(item)
item = QtWidgets.QListWidgetItem() # delimiter
item.setText('-----------------------')
item.setFlags(QtCore.Qt.NoItemFlags) # item should not be selectable
self.listWidget.addItem(item)
for f in files:
item = QtWidgets.QListWidgetItem()
item.setIcon(QtGui.Qicon('icon2.xpm'))
item.setText(f)
# set further properties like font, background ...
item.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
self.listWidget.addItem(item)
for files and folders QTreeView/QFileSystemModel might be another solution.
using QTableWidget in a corresponding way items can be grouped in rows:
来源:https://stackoverflow.com/questions/28535986/how-to-list-items-as-groups-in-qlistwidget