这是一个受布鲁斯金启发的PyQt版本。这里主要的操作差异是自定义窗口小部件类在运行时而不是编译时组成。这样做的好处是我们可以以编程方式检查目标元对象并使用它来生成代理属性。
现在PyQt是从C++编译的,所以我必须相信,它也可以在运行时在C++中生成qt类型。不过,我敢打赌那将是地狱般的。
from PyQt4 import QtGui, QtCore
def makeProxyProperty(childname, childtype, childpropname):
metaobject = childtype.staticMetaObject
metaproperty = metaobject.property(metaobject.indexOfProperty(childpropname))
def getter(self):
return metaproperty.read(getattr(self, childname))
def setter(self, val):
return metaproperty.write(getattr(self, childname), val)
return QtCore.pyqtProperty(metaproperty.typeName(), fget=getter, fset=setter)
class Widget1(QtGui.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.spinbox = QtGui.QSpinBox()
self.checkbox = QtGui.QCheckBox()
layout = QtGui.QHBoxLayout()
layout.addWidget(self.checkbox)
layout.addWidget(self.spinbox)
self.setLayout(layout)
spinbox_suffix = makeProxyProperty("spinbox", QtGui.QSpinBox, "suffix")
spinbox_prefix = makeProxyProperty("spinbox", QtGui.QSpinBox, "prefix")
spinbox_minimum = makeProxyProperty("spinbox", QtGui.QSpinBox, "minimum")
spinbox_maximum = makeProxyProperty("spinbox", QtGui.QSpinBox, "maximum")
我在寻找的东西更加自动化。我将制作包含许多基本小部件类型的自定义小部件,并且每个小部件都将有许多属性进行代理。以手动方式代理每个属性会很容易出错并且很费力。 – goertzenator
好..明白,为什么你想要子窗口小部件的属性作为主窗口小部件的属性?如果您已经将自定义小部件作为Qt-Designer插件,那么您应该可以设置/获取所有子小部件的属性 – blueskin
我有一个包含QCheckBox和QSpinBox的自定义小部件运行(从QWidget派生)。在Designer中我看不到编辑子小部件属性的方法。 – goertzenator