使用QT實現一個簡單的登陸對話框(純代碼實現C++)
效果展示
使用的QT控件
控件 描述 QLable 標簽 QLineEdit 行文本框 QPushButton 按扭 QHBoxLayout 水平布局 QVBoxLayout 垂直布局
1. 首先創建一個QT項目
這里創建一個基於QWidget的QT項目
2. 在.h中添加代碼
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
public:
// 將初始化界面的功能封裝成一個函數,避免寫到構造函數內,使其臃腫
void init();
private:
// 創建兩個QLabel標簽,兩個QLineEdit單行文本框,兩個QPushButton按扭
QLabel * userNameLb;
QLabel * passWordLb;
QLineEdit * userNameLe;
QLineEdit * passWordLe;
QPushButton * logIn;
QPushButton * logUp;
};
#endif // WIDGET_H
3. 在.cpp中添加代碼
#include "widget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
// 調用界面初始化函數
init();
}
Widget::~Widget()
{
}
void Widget::init()
{
userNameLb = new QLabel("用戶名:");
passWordLb = new QLabel;
passWordLb->setText("密 碼:");
userNameLe = new QLineEdit;
passWordLe = new QLineEdit;
logIn = new QPushButton("登陸");
logUp = new QPushButton;
logUp->setText("注冊");
// 創建三個個水平布局
QHBoxLayout * usrLayout = new QHBoxLayout;
// 將用戶名標簽和文本框添加到水平布局 ,添加的順序決定布局的順序
usrLayout->addWidget(userNameLb);
usrLayout->addWidget(userNameLe);
QHBoxLayout * pasLayout = new QHBoxLayout;
pasLayout->addWidget(passWordLb);
pasLayout->addWidget(passWordLe);
QHBoxLayout * btnLayout = new QHBoxLayout;
btnLayout->addWidget(logIn);
btnLayout->addWidget(logUp);
// 創建一個垂直布局,注意這個垂直布局需要指定父類,這里指定this,意思是將這個垂直布局設置到本窗口中
QVBoxLayout * wholeLayout = new QVBoxLayout(this);
// 從上到下順序依次將三個布局添加到這個垂直布局中,添加布局使用addLayout
wholeLayout->addLayout(usrLayout);
wholeLayout->addLayout(pasLayout);
wholeLayout->addLayout(btnLayout);
}
4. 運行效果
這時運行的效果能夠達到預期,但是有一個問題,那就是用戶可以隨意拉動窗口大小,使得界面變得不美觀
解決方法就是,可以固定窗口大小,不讓用戶能夠拖動窗口
- 在.cpp 的構造函數中添加如下代碼:
// 設置窗口固定大小
this->setFixedSize(300,150);
- 這時再運行,將鼠標放置在右下角,就不顯示可以拖動了!