How do I get my python object back from a QVariant in PyQt4?

孤人 提交于 2019-12-10 14:10:28

问题


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?


回答1:


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




回答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


来源:https://stackoverflow.com/questions/2333420/how-do-i-get-my-python-object-back-from-a-qvariant-in-pyqt4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!