我有一些问题的排序在我的项目QListView
在我指定的领域使用的值。
基本上我试图做的是这样的:
- 检测人脸的照片集并在显示它们
QListView
- 簇面(图像)
- 通过将列表中的项(其是人脸图像)属于在一起同一群集更新视图。 具体地说,如果第1项,3,5是在一个簇和物品2,4,6是在另一个,那么之前的任何项目2,4中,显示6个项目1,3,5应该被显示(在任何置换)或相反亦然。
我去了解这样做的方法是设置一个UserRole
领域各QStandardItem
在我的名单到集群标签,然后试图让QStandardModel
根据这个排序UserRole
。 那么这将显示相同的簇(即,与在相同的簇标签中的项目UserRole
)彼此相邻。
我能够设置UserRole
成功的项目,但呼吁排序功能QStandardModel
的项目并没有进行排序,即使当我设置样的角色成为默认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()