6

我正在创建一个QAbstractItemModel要显示在QTreeView.

我的index()and函数使用继承parent()的函数创建并为其提供,和需要的。在这里,出于测试目的,数据是 Python 字符串。QModelIndexQAbstractItemModelcreateIndexrowcolumndata

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>"

index()parent()data()函数中,我需要取回我的数据。它以QVariant. 如何从 QVariant 取回我的 Python 对象?

4

2 回答 2

13

你试过这个吗?

my_python_object = my_qvariant.toPyObject()

http://pyqt.sourceforge.net/Docs/PyQt4/qvariant.html#toPyObject(只是为了完整性,但那里没什么可看的......)

于 2010-02-25T12:46:34.083 回答
5

关键是internalPointer()直接在 上使用QModelIndex,根本不用处理QVariant

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
于 2010-02-25T13:16:23.317 回答