widget.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include<QLineEdit> class Widget : public QWidget { Q_OBJECT public slots: void foo(); public: Widget(QWidget *parent = 0); ~Widget(); QLineEdit *userEdit; QLineEdit * passwdEdit; }; #endif // WIDGET_H
widget.cpp
#include "widget.h" #include<QBoxLayout> #include<QGridLayout> #include<QPushButton> #include<QLabel> #include<QLineEdit> #include<QDebug> #include <QApplication> Widget::Widget(QWidget *parent) : QWidget(parent) { QGridLayout* grid=new QGridLayout(this); QHBoxLayout* hbox=new QHBoxLayout(this); QPushButton *ok=new QPushButton("确认"); QPushButton *cancel=new QPushButton("取消"); QLabel *userLabel= new QLabel("用户:"); userEdit=new QLineEdit; QLabel* passwdLabel=new QLabel("密码:"); passwdEdit=new QLineEdit; passwdEdit->setEchoMode(QLineEdit::Password); grid->addWidget(userLabel,0,0,1,1); grid->addWidget(userEdit,0,1,1,1); grid->addWidget(passwdLabel,1,0,1,1); grid->addWidget(passwdEdit,1,1,1,1); hbox->addWidget(ok); hbox->addWidget(cancel); grid->addLayout(hbox,2,0,1,2); this->setLayout(grid); connect(cancel,SIGNAL(clicked()),this,SLOT(close())); connect(ok,SIGNAL(clicked()),this,SLOT(foo())); } void Widget::foo() { if(userEdit->text()=="admin") { if(passwdEdit->text()=="123456") { qDebug()<<"登录成功"<<endl; } else { qDebug()<<"密码错误"<<endl; } } else { qDebug()<<"用户名不存在"<<endl; } } Widget::~Widget() { }
main.cpp:
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.resize(500,300); w.show(); return a.exec(); }
输出: