PyQt4.QtCore.QVariant 对象而不是字符串? [英] PyQt4.QtCore.QVariant object instead of a string?

查看:25
本文介绍了PyQt4.QtCore.QVariant 对象而不是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照这个示例 Key/Value pyqt QComboBox,将 ID 值存储到组合- 使用下面的代码框项目.

I followed this example Key/Value pyqt QComboBox, to store ID value to a combo-box item using the code below.

self.combox_widget.addItem('Apples', 'Green')
indx = self.combox_widget.currentIndex()
print self.combox_widget.itemData(indx)

但是,在尝试检索 DATA 值(上例中的Green")时,我得到 .我在这里错过了什么?

however, I get <PyQt4.QtCore.QVariant object at 0x02AC1A70> on trying to retrieve the DATA value ('Green' in the example above). What am I missing here?

推荐答案

大多数设置和检索任意数据"的 Qt API 会将其存储为 QVariant.

Most Qt APIs that set and retrieve arbitrary "data" will store it as a QVariant.

对于Python2,默认情况下,PyQt 会在您设置时自动将python 对象转换为 QVariant,但是当您设置它时,它不会自动再次将它们转换回来取回.所以你必须采取额外的步骤来做到这一点:

For Python2, by default, PyQt will automatically convert a python object to a QVariant when you set it, but it won't automatically convert them back again when you retrieve it. So you have to take an extra step to do that like this:

    print self.combox_widget.itemData(indx).toPyObject()

对于Python3,默认情况下,转换总是双向自动完成,因此不需要额外的步骤.

For Python3, by default, the conversion is always done automatically in both directions, so the extra step is not needed.

为了解决这个差异,PyQt 提供了一种明确设置默认模式的方法 使用 sip 模块:

To workaround this difference, PyQt provides a way to explicitly set the default mode by using the sip module:

import sip
sip.setapi('QVariant', 2)
from PyQt4 import QtCore, QtGui

这需要在程序开始时执行一次,在导入其他 PyQt 模块之前,并确保 QVariant 永远不会被任何 Qt API 返回.

This needs to be done once at the beginning of your program, before the other PyQt modules are imported, and will ensure that a QVariant is never returned by any Qt API.

这篇关于PyQt4.QtCore.QVariant 对象而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆