Created
June 17, 2019 05:53
-
-
Save justinfx/40e84542d3b768414d3ccbcf03b5e76d to your computer and use it in GitHub Desktop.
Minimal Qt example of adding a "virtual row" via a proxy model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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