其他分享
首页 > 其他分享> > 【QT】QT布局管理器

【QT】QT布局管理器

作者:互联网

布局管理器

image-20220116123759846

设计模式实现布局

详情见工具栏

image-20220116130800777

垂直布局,水平布局,打破布局。

代码实现布局

main.cpp

#include "testlayout.h"
#include <QApplication>
#include<QLabel>
#include<QLineEdit>
#include<QFormLayout>
#include<QRadioButton>
#include<QVBoxLayout>
#include<QPushButton>
#include<QSpacerItem>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TestLayout w;
   //添加部件并且布局
    //添加标签
    QLabel* nameLabel = new  QLabel("姓名:(&N)");
    QLabel* ageLabel = new  QLabel("年龄:(&A)");
    QLabel* emailLabel = new  QLabel("邮箱:(&E)");
    QLabel* doorLabel = new QLabel("门牌号码:");
     // 添加文本框
     QLineEdit* nameLineEdit = new QLineEdit;
     QLineEdit* ageLineEdit = new QLineEdit;
     QLineEdit* emailLineEdit = new QLineEdit;
     QLineEdit* doorNumLineEdit = new QLineEdit;


    //设置伙伴关系——绑定快捷键
    nameLabel->setBuddy(nameLineEdit);
    ageLabel->setBuddy(ageLineEdit);
    emailLabel->setBuddy(emailLineEdit);
    //添加布局
    //QFormLayout常用语表单布局
    QFormLayout* headerLayout = new QFormLayout;

    //将部件添加到布局管理器中
     headerLayout->addRow(nameLabel,nameLineEdit);
     headerLayout->addRow(ageLabel,ageLineEdit);
     headerLayout->addRow(emailLabel,emailLineEdit);
     headerLayout->addRow(doorLabel,doorNumLineEdit);
     //性别标签
     QLabel* sexLabel = new QLabel("性别:");
     //添加单选按钮
    QRadioButton* mBtn = new QRadioButton;
    QRadioButton* wBtn = new QRadioButton;
    mBtn->setText("男");
    wBtn->setText("女");
    //添加水平布局管理器
    QHBoxLayout* sexLayout = new QHBoxLayout;
    sexLayout->addWidget(sexLabel);
    sexLayout->addWidget(mBtn);
    sexLayout->addWidget(wBtn);

    //添加垂直布局管理器
    //将两个布局管理器添加到一起
    QVBoxLayout* mainLayout = new QVBoxLayout(&w);//参数-指定父窗体
    mainLayout->addLayout(headerLayout);//添加布局
    mainLayout->addLayout(sexLayout);
    //在性别选项下添加空白
    QSpacerItem* spacer = new QSpacerItem(30,30);
    mainLayout->addItem(spacer);//添加空隙对象
    //添加一个按钮
    QPushButton* okBtn = new QPushButton("确定");
    //将按钮添加到布局管理器中
    mainLayout->addWidget(okBtn);//添加部件
    mainLayout->setMargin(10);//与窗口的间隙
    mainLayout->setSpacing(20);//设置控件间的间隙
    //设置窗口布局管理器
    w.setLayout(mainLayout);
    w.show();
    return a.exec();
}

image-20220116215432704

标签:管理器,QT,布局,添加,new,include,QLabel
来源: https://blog.csdn.net/qq_51604330/article/details/122529775