如何覆盖 Pyqt 组合框 ItemText 方法,使其 returns 默认 python 字符串而不是 QString?
How to override Pyqt combobox ItemText method so it returns default python string instead of QString?
我什么时候做
resos = [_ui.ComboBox.itemText(i) for i in range(_ui.ComboBox.count())]
它给我
的列表
[PyQt4.QtCore.QString(u'1280x720 from 1.316'),
PyQt4.QtCore.QString(u'1920x1080 from 1.316'),]
如何覆盖 ComboBox 的 itemText 方法,使其只有 returns python 字符串?而不是在上面的列表理解中进行字符串转换!
你可以继承 QComboBox
:
class MyComboBox(QtGui.QComboBox):
def itemText(self, index):
return str(super(MyComboBox, self).itemText(index))
但是请注意,如果您的组合框包含非 Ascii 字符,您可能 运行 会遇到麻烦。
或者您可以尝试使用猴子修补,但这实在是太丑陋了:
def foo(combo):
def wrapper(index):
return str(QtGui.QComboBox.itemText(combo, index))
return wrapper
_ui.ComboBox.itemText = foo(_ui.ComboBox)
您可以考虑导入 sip
并更改用于 QString
的 API。将 API 版本设置为 v2 会禁用 QString
并且 PyQt 方法将 return python unicode 字符串改为
这在 PyQt4 Documentation 中有所介绍,但它的简称是:
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore
# This will raise an attribute exception because QString is only wrapped
# in version 1 of the API.
s = QtCore.QString()
由于 QtCore.QString
不存在,您将从通常 return 和 QString
.
的方法中获得本机 Python 类型
请注意,将 API 更改为 QVariant
通常也很有用,尤其是在处理 PyQt 中的模型时,以避免必须强制转换为 Python 类型。
我什么时候做
resos = [_ui.ComboBox.itemText(i) for i in range(_ui.ComboBox.count())]
它给我
的列表[PyQt4.QtCore.QString(u'1280x720 from 1.316'),
PyQt4.QtCore.QString(u'1920x1080 from 1.316'),]
如何覆盖 ComboBox 的 itemText 方法,使其只有 returns python 字符串?而不是在上面的列表理解中进行字符串转换!
你可以继承 QComboBox
:
class MyComboBox(QtGui.QComboBox):
def itemText(self, index):
return str(super(MyComboBox, self).itemText(index))
但是请注意,如果您的组合框包含非 Ascii 字符,您可能 运行 会遇到麻烦。
或者您可以尝试使用猴子修补,但这实在是太丑陋了:
def foo(combo):
def wrapper(index):
return str(QtGui.QComboBox.itemText(combo, index))
return wrapper
_ui.ComboBox.itemText = foo(_ui.ComboBox)
您可以考虑导入 sip
并更改用于 QString
的 API。将 API 版本设置为 v2 会禁用 QString
并且 PyQt 方法将 return python unicode 字符串改为
这在 PyQt4 Documentation 中有所介绍,但它的简称是:
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore
# This will raise an attribute exception because QString is only wrapped
# in version 1 of the API.
s = QtCore.QString()
由于 QtCore.QString
不存在,您将从通常 return 和 QString
.
请注意,将 API 更改为 QVariant
通常也很有用,尤其是在处理 PyQt 中的模型时,以避免必须强制转换为 Python 类型。