QT 如何使用代码实现自定义布局

除了使用QT设计师实现界面的可视化布局外,有时项目开发中需要使用代码来实现界面布局,下面给出的例子就是通过代码的方式实现界面布局的(适合新手入门):

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 
#include 
#include 
#include 
#include 


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    //ui->setupUi(this);

    QDoubleValidator* fValidator = new QDoubleValidator();
    QWidget * widget = new QWidget(this);
    QVBoxLayout * mainLayout = new QVBoxLayout();
    QHBoxLayout * horLayout = new QHBoxLayout();
    QVBoxLayout * vctLayout = new QVBoxLayout();
    //
    QLabel * _label = new QLabel("Please Enter Coordinate:");
    horLayout->addSpacing(20);
    horLayout->addWidget(_label);
    //
    QLabel * x_label = new QLabel("x:");
    QLabel * y_label = new QLabel("y:");
    QLabel * z_label = new QLabel("z:");
    QLineEdit * x_edit = new QLineEdit();
    x_edit->setValidator(fValidator);
    QLineEdit * y_edit = new QLineEdit();
    y_edit->setValidator(fValidator);
    QLineEdit * z_edit = new QLineEdit();
    z_edit->setValidator(fValidator);

    QHBoxLayout * xLayout = new QHBoxLayout();
    xLayout->addSpacing(20);
    xLayout->addWidget(x_label);
    xLayout->addWidget(x_edit);

    QHBoxLayout * yLayout = new QHBoxLayout();
    yLayout->addSpacing(20);
    yLayout->addWidget(y_label);
    yLayout->addWidget(y_edit);

    QHBoxLayout * zLayout = new QHBoxLayout();
    zLayout->addSpacing(20);
    zLayout->addWidget(z_label);
    zLayout->addWidget(z_edit);

    vctLayout->addLayout(xLayout);
    vctLayout->addLayout(yLayout);
    vctLayout->addLayout(zLayout);

    mainLayout->addLayout(horLayout);
    mainLayout->addLayout(vctLayout);
    mainLayout->addStretch();//在下方添加一个弹簧填空
    widget->setLayout(mainLayout);

    this->setCentralWidget(widget);
}

MainWindow::~MainWindow()
{
    delete ui;
}


实现的界面效果如下:
QT 如何使用代码实现自定义布局_第1张图片

你可能感兴趣的:(Qt,/,Qt,Creator,QVBoxLayout,QHBoxLayout,QIntValidator,addStretch,setLayout)