Hi all readers,

I've got a Model (a sub class of QAbstractTableModel) that work like a charm what ever the standard view I plug it in, that do not support the sort function.

But this model as 'too' many columns most of the time... (thinks of it as the result of select * from table).

So I build a simple model that filter columns, here is the code (in python) (btw I wanted to use QIdentityProxyModel but it does not exist in Qt 4.7...):
Qt Code:
  1. class ModelColumnFilter(QtGui.QSortFilterProxyModel):
  2. def __init__(self):
  3. QtGui.QSortFilterProxyModel.__init__(self)
  4. self.colMapFromSource = {} # col source -> col proxy
  5. self.colMapFromProxy = tuple() # col proxy -> col source
  6.  
  7. def set_column_to_display(self, column_to_display):
  8. self.beginResetModel()
  9. self.colMapFromProxy = tuple(column_to_display)
  10. for i, x in enumerate(self.colMapFromProxy):
  11. self.colMapFromSource[x] = i
  12. self.endResetModel()
  13.  
  14. def flags(self, index):
  15. return self.sourceModel().flags(self.mapToSource(index))
  16.  
  17. def setSourceModel(self, sourceModel):
  18. QtGui.QSortFilterProxyModel.setSourceModel(self, sourceModel)
  19. # by default display all column with same order
  20. self.set_column_to_display(
  21. tuple(i for i in xrange(self.sourceModel().columnCount())))
  22.  
  23. def columnCount(self, parent=QtCore.QModelIndex()):
  24. return len(self.colMapFromProxy)
  25.  
  26. def mapFromSource(self, sourceIndex):
  27. if sourceIndex.isValid():
  28. if sourceIndex.column() in self.colMapFromSource:
  29. return self.createIndex(sourceIndex.row(),
  30. self.colMapFromSource[sourceIndex.column()])
  31. return QtCore.QModelIndex()
  32.  
  33. def mapToSource(self, proxyIndex):
  34. if proxyIndex.isValid():
  35. return self.sourceModel().index(proxyIndex.row(),
  36. self.colMapFromProxy[proxyIndex.column()])
  37. return QtCore.QModelIndex()
To copy to clipboard, switch view to plain text mode 

So, whatever the number of view I'm using to display data in this model, they see only what I need (more over in the order I need).

This work great if I use it as is.

But if I want to sort columns, and use an other QSortFilterProxyModel like this:
Qt Code:
  1. mo = MyModel()
  2.  
  3. mf = ModelColumnFilter()
  4. mf.setSourceModel(mo)
  5. set_column_to_display([....])
  6.  
  7. mp.setSourceModel(mf)
  8.  
  9. view1 = QtGui.QTreeView()
  10. view1.setModel(mp)
  11. view1.setSortingEnabled(True)
  12.  
  13.  
  14. view2 = QtGui.QTreeView()
  15. view2.setModel(mp)
  16. view2.setSortingEnabled(True)
To copy to clipboard, switch view to plain text mode 

view2 cause the application to crash.
I suppose it's a problem in my model (an index not very well formed ??).

Tell me if I'm doing it wrong, or How can I change this to make it work.

Thanks