Qt学习(002-1)

从这一节开始做一个通讯录。基本还是分析已有的代码。
Qt5.1.1下creator建立addressbook项目。

建立头文件addressbook.h:

#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H

#include <QWidget>
#include <QLineEdit>
#include <QTextEdit>

class AddressBook : public QWidget
{
    Q_OBJECT

public:
    AddressBook(QWidget *parent = 0);

private:
    QLineEdit *nameLine;
    QTextEdit *addressText;
};


#endif // ADDRESSBOOK_H

建立源文件addressbook.cpp:

#include "addressbook.h"

#include <QLabel>
#include <QGridLayout>

AddressBook::AddressBook(QWidget *parent)
    : QWidget(parent)
{
    QLabel *nameLabel = new QLabel(tr("Name:"));
    nameLine = new QLineEdit;

    QLabel *addressLabel = new QLabel(tr("Address:"));
    addressText = new QTextEdit;

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(nameLabel, 0, 0);
    mainLayout->addWidget(nameLine, 0, 1);
    mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
    mainLayout->addWidget(addressText, 1, 1);
    setLayout(mainLayout);
    setWindowTitle(tr("Simple Address Book"));
}

AddressBook类继承自QWidget,“:QWidget(parent)”用来初始化父类。

这里使用了网格布局。其addWidget函数有两个原型:
void QGridLayout::addWidget(QWidget * widget, int row, int column, Qt::Alignment alignment = 0)


void QGridLayout::addWidget(QWidget * widget, int fromRow, int fromColumn, int rowSpan, int columnSpan, Qt::Alignment alignment = 0)

参数含义显而易见。alignment需要多解释一下:

其默认值为0,说明添加的部件会填充满指定的网格。 Qt::AlignTop指明会将部件放在网格的上部。这些指定位置的常量还有:
The horizontal flags are:

Qt::AlignLeft : Aligns with the left edge.
Qt::AlignRight  :  Aligns with the right edge.
Qt::AlignHCenter  :  Centers horizontally in the available space.
Qt::AlignJustify  :  Justifies the text in the available space.

--------
The vertical flags are:

Constant  Value Description
Qt::AlignTop  :  Aligns with the top.
Qt::AlignBottom :  Aligns with the bottom.
Qt::AlignVCenter  :  Centers vertically in the available space.

--------
You can use only one of the horizontal flags at a time. There is one two-dimensional flag:

Qt::AlignCenter  : Centers in both dimensions(AlignVCenter | AlignHCenter).



修改main.cpp:

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

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    AddressBook addressBook;
    addressBook.show();

    return a.exec();
}


运行结果:

Qt学习(002-1)

参考:

http://qt-project.org/doc/qt-4.8/tutorials-addressbook-part1.html

你可能感兴趣的:(qt)