佈局不能共享。佈局系統不是爲它設計的。
您可以使用設置功能在佈局中創建小部件並返回佈局。佈局帶有小部件。然後,您可以將該佈局應用於小部件,以此方式確定內容。設置功能可以採用自定義其行爲的參數。例如:
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