qt - 在 QT Creator 中使用自定义构造函数提升自定义小部件

标签 qt qwidget qt-designer

我知道,这基本上就是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/

相关文章:

python - TortoiseHG 图标丢失(Ubuntu Linux 16)

c++ - Qt:一行中不同大小的QLabels

python - Qt 按钮样式从 ui 预览到原始窗口各不相同

c++ - 我可以从 ui 实现 QWebView 的方法吗?

qt - 使用 Qt-Designer 自动扩展布局

c++ - 使用 Qt Table View 显示大数据

qt - QCheckBox 自动换行

c++ - 如何禁用 QWizard 中的下一步按钮

python - pyQt4:QWidget 子类不响应新的 setStyleSheet() 背景颜色

qt - 将参数传递给 QStackedWidget 中小部件的构造函数