使用 python,pyside,我得到这个错误:
self.setCheckState(value)
TypeError: could not convert 'BooleanEditor' to 'QCheckBox'
除了许多 Google 的结果只显示“TypeError: can not convert”而不是“could”,我仍然不知道如何解决这个问题。
代码片段:
class Editor(QGraphicsLayoutItem):
def __init__(self, name):
QGraphicsLayoutItem.__init__(self)
:
:
def update_value(self, value):
pass
class BooleanEditor(Editor, QCheckBox):
def __init__(self, parent, name, value, min, max):
Editor.__init__(self, name)
QCheckBox.__init__(self)
self.update_value(value)
def update_value(self, value):
self.old_value = value
self.setCheckState(value) # Error occurs here.
setCheckState 收到的“值”将为 Qt.CheckState .根据调试打印,运行时,“值”如预期的那样为 Qt.Unchecked (== 0)。
请注意,BooleanEditor 采用了多重继承。我正在将 wxWidget 应用程序(其他人制作的)移植到 Qt,现在我不想更改此设计,因为它来自原始(意味着多重继承这里本身不应该是原因,因为原始应用程序运行良好。
环境)pyside 1.1.0,python 2.7.3,Ubuntu 12.04
Update-1) 正如@Luke Woodward 所建议的,我尝试将父类(super class)的顺序交换为 BooleanEditor(QCheckBox, Editor),然后在不同的部分出现不同的错误。
class PaneGroup(GroupView, QFrame):
def __init__(self, parent, group, config, top = None):
GroupView.__init__(self, group, top)
QFrame.__init__(self)
:
sizer = QGraphicsGridLayout()
:
for param_descr in self.params:
name = param_descr['name']
type, val, min, max, description = param_descr['type'], config[name], param_descr['min'], param_descr['max'], param_descr['description']
try:
enum = eval(param_descr['edit_method'])['enum']
editor = self.top.EnumEditor(self, name, val, enum)
except:
editor = self.top._editor_types[type](self, name, val, min, max)
self.top.editors[name] = editor
sizer.addItem(editor, row, 1) # Error occurs here
错误:
TypeError: could not convert 'BooleanEditor' to 'QGraphicsLayoutItem'
在我看来,这是一个关于多重继承中初始化的问题..
请您参考如下方法:
我很糟糕,原来我使用的是 PyQt4 而不是 PySide。当我使用 PySide 时,不会发生错误(如@phihag 的要点所示),而使用 PyQt4 会产生相同的结果。这实际上很好奇,但我现在不会进一步调查。
使用以下代码进行复现。
#!/usr/bin/env python
import sys
from PySide.QtCore import Qt
from PySide.QtGui import QApplication, QCheckBox, QGraphicsLayoutItem
#from PyQt4.QtCore import Qt
#from PyQt4.QtGui import QApplication, QCheckBox, QGraphicsLayoutItem
class Editor(QGraphicsLayoutItem):
def __init__(self, name):
QGraphicsLayoutItem.__init__(self)
def update_value(self, value):
pass
class BooleanEditor(Editor, QCheckBox):
def __init__(self, value):
Editor.__init__(self, "foo")
QCheckBox.__init__(self)
self.update_value(value)
def update_value(self, value):
self.old_value = value
self.setCheckState(value) # Error occurs here
print("End of update_value")
if __name__ == "__main__":
qApp = QApplication(sys.argv)
BooleanEditor(Qt.Checked)
附言。为什么我不知道我在使用 PyQt?对于我使用的那个,我依赖于我一直在使用的这个框架(在 qt_gui 中称为 ROS, Robot Operating System),它没有明确告诉我正在使用哪个(它是开源 prj 和文档工作是正在进行中)...在破解它的代码后,我发现默认是 PyQt。
