作业:
1> 找出槽函数调用两次的原因
2> 完善登录界面,登录按钮对应的槽函数中,判断所填写账户密码是否正确,默认账户“admin”,密码“123456”
如果匹配成功,则输出登录成功并关闭界面,如果登录失败,输出登录失败,并清空密码框中的内容
点击取消按钮,则关闭界面
头文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_btn1_clicked();
void on_btn2_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
源文件:
#include "widget.h"
#include "ui_widget.h"
#include "widget.h"
#include <QDebug>
#include <QPushButton>
#include <QLabel>
#include <QLineEdit>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->btn1,&QPushButton::clicked,this,&Widget::on_btn1_clicked);
connect(ui->btn2,&QPushButton::clicked,this,&Widget::on_btn2_clicked);
ui->btn1->setIcon(QIcon("D:\\photo\\icon\\login.png"));
ui->btn2->setIcon(QIcon("D:\\photo\\icon\\cancel.png"));
ui->edit2->setEchoMode(QLineEdit::Password);
//设置窗口标题
this->setWindowTitle(this->tr("登录界面"));
//设置窗口图标
this->setWindowIcon(QIcon("D:\\photo\\111.jpg"));
//设置标签1
QLabel *lab1 = new QLabel; //无参构造
lab1->setParent(this); //设置父组件
lab1->setPixmap(QPixmap("D:\\photo\\icon\\logo.png"));
lab1->resize(800,200);
lab1->setScaledContents(true);
//设置标签2
QLabel *lab2 = new QLabel(this);
//lab2->setText("账户: ");
lab2->setPixmap(QPixmap("D:/photo/icon/userName.jpg"));
lab2->move(300,250);
lab2->resize(50,50);
lab2->setScaledContents(true);
//设置标签3
QLabel *lab3 = new QLabel(this);
lab3->setText("密码: ");
lab3->setPixmap(QPixmap("D:\\photo\\icon\\passwd.jpg"));
lab3->move(300,350);
lab3->resize(50,50);
lab3->setScaledContents(true);
// //设置登录按钮
// QPushButton *btn1 = new QPushButton;
// btn1->setParent(this);
// btn1->move(330,430);
// btn1->setIcon(QIcon("D:\\photo\\icon\\login.png"));
// btn1->resize(80,50);
// //设置取消按钮
// QPushButton *btn2 = new QPushButton;
// btn2->setParent(this);
// btn2->move(430,430);
// btn2->setIcon(QIcon("D:\\photo\\icon\\cancel.png"));
// btn2->resize(80,50);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btn1_clicked()
{
if(ui->edit1->text() == "admin" && ui->edit2->text() == "123456")
{
qDebug()<<"登录成功";
this->close();
}
else
{
qDebug()<<"登录失败";
ui->edit2->clear();
}
}
void Widget::on_btn2_clicked()
{
this->close();
}
主函数:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
代码执行结果: