QT自学笔记(二)

前言:在第一节最后我们提到了一个问题,那就是手动去布局的话太累,太繁琐。所以这一节介绍用系统自带的工具来自动布局,这个东西就是box


直接上源码

头文件:mywin2.h

#ifndef MYWIN2_H
#define MYWIN2_H

#include <QWidget>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QVBoxLayout>

class mywin2 : public QWidget
{
    Q_OBJECT

private:
    QLineEdit *m_lineEdit;
    QPlainTextEdit *m_textEdit;
    QVBoxLayout *box;



public:





    explicit mywin2(QWidget *parent = 0);


};

#endif // MYWIN2_H

mywin2.cpp:

#include "mywin2.h"

mywin2::mywin2(QWidget *parent) : QWidget(parent)
{
    m_lineEdit = new QLineEdit(this);
    m_textEdit = new QPlainTextEdit(this);

    box =new QVBoxLayout();//**注意:这里没有this**
    box->addWidget(m_lineEdit);
    box->addWidget(m_textEdit);


    this->setLayout(box);

}

main.cpp:

#include <QApplication>
#include "mywin2.h"


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    mywin2 w(NULL);
    w.setWindowTitle("layout_test");
    w.resize(400,300);
    w.move(700,300);
    w.show();
    return a.exec();
}

运行结果:

这里写图片描述

这个窗口的布局由系统自动生成,并且子窗口是随动的。


代码分析

1.在头文件中,新加入了一个类, QVBoxLayout,所以加上新的头文件。并在私有成员中声明新的成员。其他变化不大
#include <QVBoxLayout>

2.在头文件的源文件中,单行文本编辑和多行文本编辑只需要申请空间,不在进行坐标标定。而box除了要申请空间外,还要用

box->addWidget(m_lineEdit);
box->addWidget(m_textEdit);

来将m_lineEdit和m_textEdit放进去,最后再用
this->setLayout(box);
来启用这个布局。


QVBoxLayout说明

QVBoxLayout是将里面的widget采取垂直布局,而QHBoxLayout是采取水平布局。2者可套用,方法:先将两个widget采用水平布局,构成一个
QHBoxLayout1,再将另外两个widget采用水平布局,构成另一个QHBoxLayout2。最后将QHBoxLayout1,QHBoxLayout2采取垂直布局,但要使用addlayout,不再用addwidget形式。注意,QHBoxLayout1,QHBoxLayout2这两个声明的指针对象也可以作为参数放进box->addlayout中。


小节:

总结目前学到的一些:

label:插入单纯的文字,没有边框。

QLineEdit:单行文本框

QPlainTextEdit:多行文本框

QVBoxLayout:布局器

QPushButton:按钮(它里面的setText可以在上面给按钮命名)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值