views:

156

answers:

2

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?

+2  A: 

Have you tried this?

my_python_object = my_qvariant.toPyObject()

http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qvariant.html#toPyObject (just for completeness, but there isn't much to see there...)

piquadrat
This answer is more inline with the initial question. It helped me thanks
Craig
A: 

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
Didier Trosset