1

如果Qt.UserRole模型headerData()返回 Python 列表变量:

if role==Qt.UserRole:
    return QVariant(['one','two','three'])

代替常规 Python 列表的函数调用:

returnedValue = myModel(index.column(), Qt.Horizontal, Qt.UserRole)

得到一个QVariant对象:

<PyQt4.QtCore.QVariant object at 0x10d3b67c0>

尝试QVariant使用以下方法将返回的对象转换为 Python:

pythonList=returnedValue.toPyObject()

没用。我试图这样做:

对于 returnedValue.toList() 中的每个:打印每个

但这仍然会打印出一些 QVariants。应该使用什么方法将 QVariant 转换为 Python 列表?

4

1 回答 1

4

QVariant 是几乎所有内置类型的通用容器,因此为了将 QVariant 数据转换回,您需要知道它存储了什么样的数据。

from PyQt4.QtCore import QVariant

a = QVariant(['one', 'two', 'three'])

aList = [unicode(i.toString()) for i in a.toList()]
print aList

输出为:

[u'one', u'two', u'three']

于 2015-02-09T08:17:20.800 回答