我在使用指定字段中的值对QListView
中的项排序时遇到一些问题。在
基本上我要做的是:
QListView
我的方法是将列表中每个QStandardItem
的一个UserRole
字段设置为集群标签,然后尝试让QStandardModel
根据这个UserRole
进行排序。然后,这将在同一个集群中(即,UserRole
中具有相同的集群标签)中的项目彼此相邻显示。在
我能够成功地为项目设置UserRole
,但是调用QStandardModel
上的sort函数并没有对项目进行排序,即使我将sort角色设置为默认的DisplayRole
(即根据每个面的文本标签进行排序),它也能正常工作。在
有人能告诉我我的代码有什么问题吗,或者提供一种替代方法吗?我在google上搜索了排序列表,在QSortFilterProxyModel上找到了下面的链接,但由于我对Qt还比较陌生,所以我无法将其适应我的情况。在
提前感谢您的回复。在
以下是相关代码:
import os
from PySide.QtGui import QListView, QStandardItemModel, QStandardItem, QIcon
from PySide.QtCore import Qt
class FacesView(QListView):
"""
View to display detected faces for user to see and label.
"""
UNCLUSTERED_LABEL = -1
CLUSTER_ROLE = Qt.UserRole + 1
def __init__(self, *args):
super(FacesView, self).__init__(*args)
self._dataModel = QStandardItemModel()
self.setModel(self._dataModel)
# Layout items in batches instead of waiting for all items to be
# loaded before user is allowed to interact with them.
self.setLayoutMode(QListView.Batched)
def updateFaceClusters(self, labels):
"""Update the cluster label for each face.
@param labels: [1 x N] array where each element is an integer
for the cluster the face belongs to."""
assert(len(labels) == self._dataModel.rowCount())
# Put the cluster label each item/face belong to in the
# CLUSTER_ROLE field.
for i in xrange(self._dataModel.rowCount()):
index = self._dataModel.index(i, 0)
self._dataModel.setData(index, labels[i], self.CLUSTER_ROLE)
# Use cluster label as sort role
self._dataModel.setSortRole(self.CLUSTER_ROLE)
# This does NOT seem to sort the items even though it works fine
# when sort role is the default Qt.DisplayRole.
self._dataModel.sort(0)
print("Finished updating face clusters")
def itemsInList(self):
"""Returns the label for a face and the path to its image.
@return: (label, path)"""
items = []
for i in xrange(self._dataModel.rowCount()):
label = self._dataModel.index(i, 0).data(Qt.DisplayRole)
imagePath = self._dataModel.index(i, 0).data(Qt.UserRole)
clusterLabel = self._dataModel.index(i, 0).data(self.CLUSTER_ROLE)
items.append((imagePath, label, clusterLabel))
return items
def addItem(self, label, imagePath):
"""Add an item to list view
@param label: The label associated with the item.
@param imagePath: Path to image for the icon."""
if os.path.exists(imagePath):
icon = QIcon(imagePath)
else:
icon = QIcon(':/res/Unknown-person.gif')
item = QStandardItem(icon, label)
item.setEditable(True)
# Add image path to the UserRole field.
item.setData(imagePath, Qt.UserRole)
# Add cluster label to image. CLUSTER_ROLE is where I intend
# to put the item's cluster label.
item.setData(self.UNCLUSTERED_LABEL, self.CLUSTER_ROLE)
# Prevent an item from dropping into another item.
item.setDropEnabled(False)
# Add item to list indirectly by adding it to the model.
self._dataModel.appendRow(item)
def clear(self):
self._dataModel.clear()
你发布的代码没有问题。所以你使用它的方式一定有问题。如何生成簇标签?在
下面是一个使用您的
FacesView
类的测试脚本,它按您的预期进行排序:相关问题 更多 >
编程相关推荐