2012-01-27 124 views

回答

4

你可以使用一個QSortFilterProxyModel並重新實​​現其lessThan方法。

或者,創建一個QStandardItem的子類並重新實現其運算符less than

這裏有一個簡單的例子,演示了後一種方法:

from random import sample 
from PyQt4 import QtGui, QtCore 

class Window(QtGui.QWidget): 
    def __init__(self): 
     QtGui.QWidget.__init__(self) 
     self.view = QtGui.QTreeView(self) 
     self.view.setHeaderHidden(True) 
     self.model = QtGui.QStandardItemModel(self.view) 
     self.view.setModel(self.model) 
     parent = self.model.invisibleRootItem() 
     keys = range(65, 91) 
     for key in sample(keys, 10): 
      item = StandardItem('Item %s' % chr(key), False) 
      parent.appendRow(item) 
      for key in sample(keys, 10): 
       item.appendRow(StandardItem('Child %s' % chr(key))) 
     self.view.sortByColumn(0, QtCore.Qt.AscendingOrder) 
     layout = QtGui.QVBoxLayout(self) 
     layout.addWidget(self.view) 

class StandardItem(QtGui.QStandardItem): 
    def __init__(self, text, sortable=True): 
     QtGui.QStandardItem.__init__(self, text) 
     self.sortable = sortable 

    def __lt__(self, other): 
     if getattr(self.parent(), 'sortable', True): 
      return QtGui.QStandardItem.__lt__(self, other) 
     return False 

if __name__ == '__main__': 

    import sys 
    app = QtGui.QApplication(sys.argv) 
    window = Window() 
    window.show() 
    sys.exit(app.exec_()) 
+0

so,key - 如果item不可排序(如果item在我的情況下不是頂級項目),則返回__lt__ compassion上的False? – 2012-01-27 21:19:29

+1

@Andrewshkovskii。是。在你的情況下,它看起來像你可以使用普通的'QStandardItem'作爲頂層項目,然後從'__lt__'中爲所有子項目返回'False'(因此不需要'sortable'屬性)。 – ekhumoro 2012-01-27 21:42:23

+0

謝謝,我會盡力:) – 2012-01-28 07:40:32

1

在您的QTreeView實例上調用setSortingEnabled(bool)Here是對C對應的實況++和here是鏈接到PyQt的API實況此功能

+1

我不需要禁用排序的所有項目,只爲孩子的物品; – 2012-01-27 06:27:09