use setIndexWidget(QModelIndex, QWidget)
to set custom QWidget
- set QListView proxy model, use
QSortFilterProxyModel
- rewrite
lessThan
method to sort
Demand:
- 5 categories(Tang, Song, Yuan, Ming, Qing) and Unclassified
- selected Tang, the result is Tang, Song, Yuan, Ming, Qing, Unclassified
- selected Song, the result is Song, Tang, Yuan, Ming, Qing, Unclassified
- selected Yuan, the result is Yuan, Tang, Song, Ming, Qing, Unclassified
- Cancel sorting then Restore, like: Unclassified, Tang, Tang, Ming, Qing, Unclassified, Song, Yuan, Unclassified
Method:
- define
IdRole = Qt.UserRole + 1
Used to restore default sort - define
ClassifyRole = Qt.UserRole + 2
Used for sorting by sorting number - define 5 classify id
NameDict = { 'Tang': ['Tang', 0], 'Song': ['Song', 1], 'Yuan': ['Yuan', 2], 'Ming': ['Ming', 3], 'Qing': ['Qing', 4], } IndexDict = { 0: 'Tang', 1: 'Song', 2: 'Yuan', 3: 'Ming', 4: 'Qing', }
- item
setData(id, IdRole)
Used to restore default sort - item
setData(cid, ClassifyRole)
Used to record classification - inherit
QSortFilterProxyModel
and addsetSortIndex(self, index)
mthod, The purpose is to keep some classify always topdef setSortIndex(self, index): self._topIndex = index
- inherit
QSortFilterProxyModel
and rewritelessThan
mthod, if classify id is equal to top id, then modify it -1if self.sortRole() == ClassifyRole and \ source_left.column() == self.sortColumn() and \ source_right.column() == self.sortColumn(): # get classify id leftIndex = source_left.data(ClassifyRole) rightIndex = source_right.data(ClassifyRole) # AscendingOrder if self.sortOrder() == Qt.AscendingOrder: # keep always top if leftIndex == self._topIndex: leftIndex = -1 if rightIndex == self._topIndex: rightIndex = -1 return leftIndex < rightIndex
- restore default sort
self.fmodel.setSortRole(IdRole) self.fmodel.sort(0)
- sort by classify id, must reset
setSortRole
to otherself.fmodel.setSortIndex(1) self.fmodel.setSortRole(IdRole) self.fmodel.setSortRole(ClassifyRole) self.fmodel.sort(0)