我有复杂的GUI设计,我想最少使用QLayout来获得更易读的代码。 我曾经使用过QGridLayout和QBoxLayout,但代码不可读。 我的代码的简短版本请建议修改,以便代码更具可读性
QVBoxLayout *mainLayout = new QVBoxLayout(this); // Main Layout
// First GroupBox QGroupBox
QGroupBox *GroupBox1 = new QGroupBox();
QHBoxLayout *Layout1 = new QHBoxLayout(); // Layout1 contains 3 Line edits
GroupBox1->setLayout(Layout1);
// Second Group table Group Box
QGroupBox *GroupBox2 = new QGroupBox("Second Group", this);
// GroupBox2 contains table Widget and Buttons
QHBoxLayout *tableWrapperLayout = new QHBoxLayout();
QVBoxLayout *TableWidgetLayout1 = new QVBoxLayout();
QVBoxLayout *TableButtonLayout1 = new QVBoxLayout();
GroupBox2->setLayout(tableWrapperLayout);
// Param Table widget
QGroupBox *GroupBox3 = new QGroupBox("Third Group", this); // Same as GroupBox3
QHBoxLayout *TableWrapperLayout1 = new QHBoxLayout();
QVBoxLayout *TableWidgetLayout2 = new QVBoxLayout();
QVBoxLayout *TableButtonLayout2 = new QVBoxLayout();
GroupBox3->setLayout(TableWrapperLayout1);
QHBoxLayout *groupWrapperLayout = new QHBoxLayout();
// This is Wrapper for GroupBox2 and GroupBox3
groupWrapperLayout->addWidget(GroupBox2);
groupWrapperLayout->addWidget(GroupBox3);
// Main Layout contains GroupBox1 and groupWrapper
mainLayout->addWidget(GroupBox1);
mainLayout->addLayout(groupWrapperLayout);
答案 0 :(得分:1)
我不知道它有什么难以理解的东西,但在这里它的冗长程度要低一些。一般来说,您不需要使用框布局,网格布局可以做所有框布局都可以做到的。您也不需要为布局管理的小部件设置父级。
在实际代码中,您当然不会在堆上创建所有按钮/编辑,而只需将它们添加为Widget
类的成员,然后将它们逐个添加到布局中一。为简洁起见,我使用了循环和堆分配。
#include <QApplication>
#include <QGridLayout>
#include <QLineEdit>
#include <QGroupBox>
#include <QTableWidget>
#include <QPushButton>
class Widget : public QWidget {
QGridLayout m_layout;
QGroupBox m_group1;
QGridLayout m_group1Layout;
QGroupBox m_group2;
QGridLayout m_group2Layout;
QGroupBox m_group3;
QGridLayout m_group3Layout;
public:
Widget(QWidget * parent = 0) : QWidget(parent),
m_layout(this),
m_group1("First Group"),
m_group1Layout(&m_group1),
m_group2("Second Group"),
m_group2Layout(&m_group2),
m_group3("Third Group"),
m_group3Layout(&m_group3)
{
m_layout.addWidget(&m_group1, 0, 0, 1, 2);
m_layout.addWidget(&m_group2, 1, 0);
m_layout.addWidget(&m_group3, 1, 1);
// Line edits in group 1
for (int i = 0; i < 3; ++ i)
m_group1Layout.addWidget(new QLineEdit, 0, i);
// Table and buttons in group 2
m_group2Layout.addWidget(new QTableWidget, 0, 0, 4, 1);
for (int i = 0; i < 4; ++ i)
m_group2Layout.addWidget(new QPushButton(QString::number(i)), i, 1);
// Table and buttons in group 3
m_group3Layout.addWidget(new QTableWidget, 0, 0, 4, 1);
for (int i = 0; i < 4; ++ i)
m_group3Layout.addWidget(new QPushButton(QString::number(i)), i, 1);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}