문제

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

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

다른 팁

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...)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top