头文件: .h
#ifndef MYDIALOG_H
#define MYDIALOG_H
#include <QtGui/QDialog>
#include "ui_mydialog.h"
#include <QtCore/QTextCodec>
class QLineEdit;
class mydialog : public QDialog
{
Q_OBJECT
public:
mydialog(QWidget *parent = 0, Qt::WFlags flags = 0);
~mydialog();
public slots:
virtual void accept();
private:
Ui::mydialogClass ui;
QLineEdit* usrLineEdit;
QLineEdit* pwdLineEdit;
};
#endif // MYDIALOG_H
实现文件: .cpp
#include "mydialog.h"
#include <QtGui/QtGui>
mydialog::mydialog(QWidget *parent, Qt::WFlags flags)
: QDialog(parent, flags)
{
ui.setupUi(this);
QLabel*usrLable=new QLabel(tr("用户名:"));
QLabel*pwdLable=new QLabel(tr("密 码:"));
usrLineEdit = new QLineEdit;
pwdLineEdit = new QLineEdit;
pwdLineEdit->setEchoMode(QLineEdit::Password);// 采用*号代替用户输入的字符
//用户名: zhaotong
//密 码: *****
QGridLayout*gridLayout=new QGridLayout;
gridLayout->addWidget(usrLable,0,0,1,1); //五个值分别代表usrLineEdit指出哪一个窗口
gridLayout->addWidget(usrLineEdit,0,1,1,3);//部件将被放置在网络布局管理器gridLayout中
gridLayout->addWidget(pwdLable,1,0,1,1);//后边4个值:前两个表示行和列的位置,后边两个值表示
gridLayout->addWidget(pwdLineEdit,1,1,1,3);//行的跨度和列的跨度
//建立 确定,取消 按钮
QPushButton*okBtn=new QPushButton(tr("确定"));
QPushButton*cancelBtn=new QPushButton(tr("取消"));
QHBoxLayout*btnlayout=new QHBoxLayout;//
btnlayout->setSpacing(60);//两个内部按钮之间的距离
btnlayout->addWidget(okBtn);
btnlayout->addWidget(cancelBtn);
//建立一个垂直布局管理器
QVBoxLayout*dlgLayout=new QVBoxLayout;
dlgLayout->setMargin(40);//边框和边框的距离
dlgLayout->addLayout(gridLayout);
dlgLayout->addStretch(40);
dlgLayout->addLayout(btnlayout);
setLayout(dlgLayout);
connect(okBtn,SIGNAL(clicked()),this,SLOT(accept()));
connect(cancelBtn,SIGNAL(clicked()),this,SLOT(reject()));
setWindowTitle(tr("登陆"));
resize(300,200);
}
void mydialog::accept()
{
if (usrLineEdit->text().trimmed()==tr("zhaotong")&&pwdLineEdit->text()==tr("zhaotong"))
{
QDialog::accept();
}
else
{
QMessageBox::warning(this,tr("警告"),tr("用户名或密码错误!"),QMessageBox::Yes);
usrLineEdit->setFocus();//限定鼠标只可以在最上边的窗口活动,即模态对话框
//QMessageBox::aboutQt(this,tr("猜猜看"));
}
}
mydialog::~mydialog()
{
}
主程序文件: .cpp
#include "mydialog.h"
#include <QtGui/QApplication>
#include <QtGui/QtGui>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("gb18030"));//显示汉字,要包含头文件<QtCore/QTextCodec>
QTranslator tanslator;
{
QStringList environment=QProcess::systemEnvironment();
QString str;
bool bFinded=false;
foreach(str,environment)//foreach(variable变量,container容器),遍历container,把列表项存放在variable中
{
if (str.startsWith("QTDIR="))//查找QTDIR
{
bFinded=true;
break;
}
}
//下边代码是给应用程序安装翻译器(translator)
if(bFinded)
{
str=str.mid(6);//存在QTDIR,通过QString::mid()函数获取环境变量的值(去掉字符串QTDIR=后的内容,即QT的安装路径)
bFinded=tanslator.load("qt_"+QLocale::system().name(),str.append("/tanslations/"));
if (bFinded)
qApp->installTranslator(&tanslator);
else
qDebug()<<QObject::tr("没有支持中文的QT国际化翻译软件");
}
else
{
qDebug()<<QObject::tr("必须设置QTDIR环境变量!");
exit(1);
}
}
mydialog w;
w.show();
return a.exec();
}