我知道,这基本上就是the same question ,但我的问题更进一步。
下面的树解释了我的结构:
QWidget
|
CustomWidget
| |
MyTable MyWidgetAroundIt
我在 Qt Designer 中升级了 MyTable
。因此,我可以将其添加到 MyWidgetAroundIt
中。这非常有效。唯一的问题是,CustomWidget
要求它的父级也是 CustomWidget
,它的构造函数如下所示:
CustomWidget(CustomWidget* parent) : QWidget(parent), _specialValue(parent->getSpecialValue)
这会导致编译错误,因为设计器生成的代码尝试使用 QWidget*
(而不是 CustomWidget*
)初始化 MyTable
。我可以/应该做什么来防止这种情况和/或向设计师提供有关此要求的提示?
最佳答案
父级不能是 QWidget
的小部件不再是小部件。您的设计违反了里氏替换原则,必须予以修复。
如果小部件恰好属于某种类型,您可以自由启用特殊功能,但小部件必须可与父级的任何小部件一起使用。
因此:
CustomWidget(QWidget* parent = nullptr) :
QWidget(parent)
{
auto customParent = qobject_cast<CustomWidget*>(parent);
if (customParent)
_specialValue = customParent->specialValue();
}
或者:
class CustomWidget : public QWidget {
Q_OBJECT
CustomWidget *_customParent = qobject_cast<CustomWidget*>(parent());
SpecialType _specialValue = _customParent ? _customParent->specialValue() : SpecialType();
SpecialType specialValue() const { return _specialValue; }
public:
CustomWidget(QWidget * parent = nullptr) : QWidget(parent) {}
};
关于qt - 在 QT Creator 中使用自定义构造函数提升自定义小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41872674/