Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Minimal Qt example of adding a "virtual row" via a proxy model
#!/usr/bin/env python
"""
Refs:
"[Maya-Python] Customized display of files/folders in a QTreeView that is using QFileSystemModel."
https://groups.google.com/d/topic/python_inside_maya/TaFm2yNToJ8/discussion
"""
from PySide import QtCore, QtGui
class VirtualRowProxyModel(QtGui.QSortFilterProxyModel):
# Some internal id indicating when its a virtual row
IS_VIRTUAL = -1
def mapToSource(self, proxyIndex):
if self._isVirtualRow(proxyIndex):
return QtCore.QModelIndex()
return super(VirtualRowProxyModel, self).mapToSource(proxyIndex)
def index(self, row, column, parent=QtCore.QModelIndex()):
model = self.sourceModel()
sourceParent = self.mapToSource(parent)
sourceRows = model.rowCount(sourceParent)
if row >= sourceRows:
return self.createIndex(row, column, self.IS_VIRTUAL)
return super(VirtualRowProxyModel, self).index(row, column, parent)
def parent(self, index):
if self._isVirtualRow(index):
return QtCore.QModelIndex()
return super(VirtualRowProxyModel, self).parent(index)
def data(self, proxyIndex, role=QtCore.Qt.DisplayRole):
if self._isVirtualRow(proxyIndex):
if role == QtCore.Qt.DisplayRole:
return "-VIRTUAL ROW-"
return None
return super(VirtualRowProxyModel, self).data(proxyIndex, role)
def rowCount(self, parent=QtCore.QModelIndex()):
return self.sourceModel().rowCount(self.mapToSource(parent)) + 1
def _isVirtualRow(self, index):
return index.isValid() and index.internalId() == self.IS_VIRTUAL
if __name__ == '__main__':
app = QtGui.QApplication([])
view = QtGui.QTreeView()
model = QtGui.QStandardItemModel()
model.appendRow(QtGui.QStandardItem("A"))
model.appendRow(QtGui.QStandardItem("B"))
model.appendRow(QtGui.QStandardItem("C"))
proxy = VirtualRowProxyModel()
proxy.setSourceModel(model)
view.setModel(proxy)
view.resize(800, 600)
view.show()
view.raise_()
app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment