布局不能共享。布局系统不是为它设计的。
您可以使用设置功能在布局中创建小部件并返回布局。布局带有小部件。然后,您可以将该布局应用于小部件,以此方式确定内容。设置功能可以采用自定义其行为的参数。例如:
enum WidgetType {
Normal, WithButton, WithCombo
};
QGridLayout* setup(WidgetType type) {
auto l = new QGridLayout;
l.addWidget(0, 0, new QLabel("Hello"));
l.addWidget(0, 1, new QLabel("World"));
switch (type) {
case WithButton:
l.addWidget(1, 0, new QPushButton("Click Me!"));
break;
case WithCombo:
if (auto combo = new QComboBox) {
...
l.addWidget(1, 1, combo);
}
break;
case Normal:
break;
}
return l;
};
void test() {
QWidget w1, w2;
w1.setLayout(setup(Normal));
w2.setLayout(setup(WithButton));
}
当然,大概您会想要轻松引用小部件。因此,它是您创建一个能够采取multple表单的自定义窗口小部件最好,并根据需要通过值或指针指向小部件:
class Widget : public QWidget {
QGridLayout m_layout{this};
QLabel m_label1("Hello");
QLabel m_label2("World");
QPointer<QPushButton> m_button;
QPointer<QComboBox> m_combo;
public:
Widget(WidgetType type, QWidget *parent = nullptr) : QWidget(parent) {
m_layout.addWidget(0, 0, &m_label1);
m_layout.addWidget(0, 1, &m_label2);
switch (type) {
case WithButton:
m_button = new QPushButton("Click Me!");
m_layout.addWidget(1, 0, m_button.data());
break;
case WithCombo:
m_combo = new QComboBox;
...
m_layout.addWidget(1, 1, m_combo.data());
break;
case Normal:
break;
}
}
};
“干净的解决方案”是为了什么?你还没有解释你想要解决什么问题。 – ekhumoro