【问题标题】:How to get Python List from QVariant如何从 QVariant 获取 Python 列表
【发布时间】:2015-02-09 08:09:13
【问题描述】:

如果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()

没用。我已经尝试过:

对于返回值.toList() 中的每个: 打印每个

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

【问题讨论】:

    标签: python list qt pyqt qvariant


    【解决方案1】:

    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']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      相关资源
      最近更新 更多