I am creating a subclass of QAbstractItemModel to be displayed in an QTreeView.
My index() and parent() function creates the QModelIndex using the QAbstractItemModel inherited function createIndex and providing it the row, column, and data needed. Here, for testing purposes, data is a Python string.
class TestModel(QAbstractItemModel):
def __init__(self):
QAbstractItemModel.__init__(self)
def index(self, row, column, parent):
if parent.isValid():
return self.createIndex(row, column, "bar")
return self.createIndex(row, column, "foo")
def parent(self, index):
if index.isValid():
if index.data().data() == "bar": <--- NEVER TRUE
return self.createIndex(0, 0, "foo")
return QModelIndex()
def rowCount(self, index):
if index.isValid():
if index.data().data() == "bar": <--- NEVER TRUE
return 0
return 1
def columnCount(self, index):
return 1
def data(self, index, role):
if index.isValid():
return index.data().data() <--- CANNOT DO ANYTHING WITH IT
return "<None>"
Within the index(), parent(), and data() functions I need to get my data back. It comes as a QVariant. How do I get my Python object back from the QVariant?
Have you tried this?
my_python_object = my_qvariant.toPyObject()
http://pyqt.sourceforge.net/Docs/PyQt4/qvariant.html#toPyObject (just for completeness, but there isn't much to see there...)
The key thing is to use internalPointer() directly on the QModelIndex, not dealing with the QVariant at all.
class TestModel(QAbstractItemModel):
def __init__(self, plan):
QAbstractItemModel.__init__(self)
def index(self, row, column, parent):
if not parent.isValid():
return self.createIndex(row, column, "foo")
return self.createIndex(row, column, "bar")
def parent(self, index):
if index.internalPointer() == "bar":
return self.createIndex(0, 0, "foo")
return QModelIndex()
def rowCount(self, index):
if index.internalPointer() == "bar":
return 0
return 1
def columnCount(self, index):
return 1
def data(self, index, role):
if role == 0: # Qt.DisplayRole
return index.internalPointer()
else:
return None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With