一.登录对话框需求分析
二.代码实现
main.c:
#include <QtGui/QApplication>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
Widget.h:
#ifndef _WIDGET_H_
#define _WIDGET_H_
#include <QtGui/QWidget>
#include <QPushButton>
class Widget : public QWidget
{
Q_OBJECT
private:
QPushButton TestBtn;
private slots:
void TestBtn_Clicked();
public:
Widget(QWidget *parent = 0);
~Widget();
};
#endif
Widget.cpp:
#include "Widget.h"
#include "QLoginDialog.h"
#include <QDebug>
Widget::Widget(QWidget *parent) : QWidget(parent), TestBtn(this)
{
TestBtn.setText("Test Login Dialog");
setFixedSize(200, 50);
connect(&TestBtn, SIGNAL(clicked()), this, SLOT(TestBtn_Clicked()));
}
void Widget::TestBtn_Clicked()
{
QLoginDialog dlg;
if( dlg.exec() == QDialog::Accepted )
{
qDebug() << "User: " + dlg.getUser();
qDebug() << "Pwd: " + dlg.getPwd();
}
}
Widget::~Widget()
{
}
QLoginDialog.h :
#ifndef _QLOGINDIALOG_H_
#define _QLOGINDIALOG_H_
#include <QtGui/QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
class QLoginDialog : public QDialog
{
Q_OBJECT
private:
QLabel UserLabel;
QLabel PwdLabel;
QLineEdit UserEdit;
QLineEdit PwdEdit;
QPushButton LoginBtn;
QPushButton CancelBtn;
QString m_user;
QString m_pwd;
private slots:
void LoginBtn_Clicked();
void CancelBtn_Clicked();
public:
QLoginDialog(QWidget *parent = 0);
QString getUser();
QString getPwd();
~QLoginDialog();
};
#endif
QLoginDialog.c:
#include "QLoginDialog.h"
#include <QDebug>
QLoginDialog::QLoginDialog(QWidget* parent) : QDialog(parent, Qt::WindowCloseButtonHint),
UserLabel(this), PwdLabel(this), UserEdit(this), PwdEdit(this), LoginBtn(this), CancelBtn(this)
{
UserLabel.setText("User ID:");
UserLabel.move(20, 30);
UserLabel.resize(60, 25);
UserEdit.move(85, 30);
UserEdit.resize(180, 25);
PwdLabel.setText("Password:");
PwdLabel.move(20, 65);
PwdLabel.resize(60,25);
PwdEdit.move(85, 65);
PwdEdit.resize(180, 25);
PwdEdit.setEchoMode(QLineEdit::Password);
CancelBtn.setText("Cancel");
CancelBtn.move(85, 110);
CancelBtn.resize(85, 30);
LoginBtn.setText("Login");
LoginBtn.move(180, 110);
LoginBtn.resize(85, 30);
setWindowTitle("Login");
setFixedSize(285, 170);
connect(&LoginBtn, SIGNAL(clicked()), this, SLOT(LoginBtn_Clicked()));
connect(&CancelBtn, SIGNAL(clicked()), this, SLOT(CancelBtn_Clicked()));
}
void QLoginDialog::LoginBtn_Clicked()
{
qDebug() << "LoginBtn_Clicked() Begin";
m_user = UserEdit.text().trimmed();
m_pwd = PwdEdit.text();
done(Accepted);
qDebug() << "LoginBtn_Clicked() End";
}
void QLoginDialog::CancelBtn_Clicked()
{
qDebug() << "CancelBtn_Clicked() Begin";
done(Rejected);
qDebug() << "CancelBtn_Clicked() End";
}
QString QLoginDialog::getUser()
{
return m_user;
}
QString QLoginDialog::getPwd()
{
return m_pwd;
}
QLoginDialog::~QLoginDialog()
{
}
运行结果: