问题描述
我正在创建QAbstractItemModel
的子类,以显示在QTreeView
中.
I am creating a subclass of QAbstractItemModel
to be displayed in an QTreeView
.
我的index()
和parent()
函数使用QAbstractItemModel
继承的函数createIndex
并提供所需的row
,column
和data
来创建QModelIndex
.在这里,出于测试目的,数据是一个Python字符串.
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>"
在index()
,parent()
和data()
函数中,我需要取回数据.它以QVariant
的形式出现.如何从QVariant取回我的Python对象?
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?
推荐答案
关键是直接在QModelIndex
上使用internalPointer()
,而根本不使用QVariant
.
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
这篇关于如何从PyQt4中的QVariant取回python对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!