PDA

View Full Version : Getting proper root index for QTreeView with QSortFilterProxyModel



JediAce
3rd March 2011, 20:31
Hi Everyone

So I'm trying to filter a QFileSystemModel using QSortFilterProxyModel and displaying it with QTreeView. The filtering works fine, however, I'm having trouble setting the root index to the folder I want. To set the root index for QTreeView, I use:

someTreeView.setRootIndex( someFilterProxyModel.mapFromSource(indexFromSource ))

after some debugging I realized that the index outputted by

someFIlterProxyModel.mapFromSource(indexFromSource ) is invalid. Here is some sample code:



154 # Add file browser
155 model = QFileSystemModel()
156 testDir = QString(dir)
157 model.setRootPath(testDir)
158 self._fsModel = model
159 self._treeView = QTreeView()
160
161 if self.selectedFileFilter == 'All Files':
162 self._treeView.setModel(model)
163 self._treeView.setRootIndex(model.index(testDir))
164 else:
165 filteredModel = FileSystemFilter()
166 filteredModel.setSourceModel(self._fsModel)
167 ext = self.selectedFileFilter.split(' ')[0]
168 pattern = '*' + ext
169 print 'pattern: %s' % pattern
171 filteredModel.setFilterWildcard(QString('*.spy'))
172 filteredModel.setDynamicSortFilter(True)
175 self._treeView.setModel(filteredModel)
176 print 'model index is valid: %s' % model.index(testDir).isValid()
177 print 'proxy index is valid: %s' % filteredModel.mapFromSource(model.index(testDir)). isValid()
179 self._treeView.setRootIndex(filteredModel.mapFromS ource(model.index(testDir)))


Sorry the lines are off. I deleted some comments. Does anyone know why this is happening? Is this a known bug? Is there any other way to get the root index from my source model? Thanks.

wysota
6th March 2011, 08:48
QFileSystemModel initializes itself in the background so it may take a while until a specified index is valid. Instead you should just set the root path of the model to the path you expect to have as a root index of the view. Unfortunately you won't be able to go up the directory structure then. Another solution is to wait until the model gets initialized or use QDirModel.