代码如下:widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSqlTableModel>
#include <qstringlist>
#include <qstringlistmodel>
#include "login.h"
#include "datatype.h"
#include "clientsocket.h"
#include "registerdialog.h"
#include <QCloseEvent>
#define SERVERADDRESS "219.222.170.15"
#define SERVERPORT 3800
namespace Ui {
class Widget;
}
class Widget : public QWidget//, public Ui::Widget
{
Q_OBJECT
public:
explicit Widget(QString n, QString p, QWidget *parent = 0);
Widget(QWidget *parent = 0);
~Widget();
protected:
void closeEvent(QCloseEvent *event);
Ui::Widget *ui;
private:
QString username;
QString password;
QString selfname;
QSqlTableModel *model;
ClientSocket client;
login *loginDialog;
RegisterDialog *registerDialog;
QStringList nameList;
QStringListModel nameModel;
void makeConnections();
void logining();
private slots:
void showConnectedInLabel();
void showDisconnectedInLabel();
void sendMessage();
void addNewComerToNameList(const QString &newName,const QHostAddress &address);
void showMessageInTextEdit(const QString &hisName,const QString ¤tDateTime,const QString &message);
void removeLeaverNameFromNameList(const QString &name);
void nameAndPasswordIsNotRight();
void nameAndPasswordIsRight();
void showRegisterDialog();
void tryToConnectToServer();
void registerSuccess();
void registerFailed();
void tryToRegister();
void goBackToLoginDialog();
};
#endif // WIDGET_H
login.h:
#ifndef LOGIN_H
#define LOGIN_H
#include <QDialog>
#include "ui_login.h"
/*
namespace Ui {
class login;
}*/
class login : public QDialog,public Ui::login
{
Q_OBJECT
public:
login(QWidget *parent = 0);
QString GetName();
QString GetPwd();
~login();
protected:
void changeEvent(QEvent *e);
private:
Ui::login *ui;
private slots:
/* void on_registerButton_clicked();
void on_forgetButton_clicked();
void on_saveButton_clicked();
void on_autorloginBox_clicked();
void on_setButton_clicked();
void on_loginButton_clicked();*/
void setloginButtonEnable(const QString &name);
private:
QString username;
QString password;
};
#endif // LOGIN_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <qdatastream>
#include <qbytearray>
#include <qmessagebox>
#include <qdatetime>
#include "login.h"
#include <qhostaddress>
#include <qsizepolicy>
//#include <stdio.h>
Widget::Widget(QString n, QString p, QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
username = n;
password = p;
model = new QSqlTableModel(this);
model->setTable("user");
model->setFilter(tr("username = '%1'").arg(username));
model->select();
ui->label->setText(tr("%1,欢迎您!").arg(username));
ui->selfnamelabel->setText(tr("%2").arg(selfname));
setFixedSize(width(),height());
setAttribute(Qt::WA_DeleteOnClose);
makeConnections();
logining();
}
//============================================================================
//
// 进入loginDialog
//
//============================================================================
void Widget::logining()
{
loginDialog=new login(this);
loginDialog->show();
connect(loginDialog->registerButton,SIGNAL(clicked()),this,SLOT(showRegisterDialog()));
connect(loginDialog->loginButton,SIGNAL(clicked()),this,SLOT(tryToConnectToServer()));
}
void Widget::showConnectedInLabel()
{
ui->stateLabel->setText(tr("connected"));
}
void Widget::showDisconnectedInLabel()
{
ui->stateLabel->setText(tr("disconnected"));
}
//============================================================================
//
// 进入registerDialog
//
//============================================================================
void Widget::showRegisterDialog()
{
loginDialog->hide();
registerDialog=new RegisterDialog(this);
registerDialog->show();
connect(registerDialog->okButton,SIGNAL(clicked()),this,SLOT(tryToRegister()));
connect(registerDialog->concelButton,SIGNAL(clicked()),this,SLOT(goBackToLoginDialog()));
}
//============================================================================
//
// 向服务器发注册信息
//
//============================================================================
void Widget::tryToRegister()
{
if(client.state()==QAbstractSocket::UnconnectedState){
client.connectToHost(QHostAddress(SERVERADDRESS),SERVERPORT);
if(!client.waitForConnected(3000)){
QMessageBox::warning(registerDialog,
tr("!!!"),
tr("failed to connect"));
}
client.isRegistering=true;
}
QString name=registerDialog->nameLineEdit->text();
QString password=registerDialog->passwordLineEdit->text();
QString passwordAgain=registerDialog->passwordAgainLineEdit->text();
if(name.isEmpty()){
QMessageBox::warning(registerDialog,
tr("!!!"),
tr("invalid name"));
}
else if(password!=passwordAgain){
QMessageBox::warning(registerDialog,
tr("!!!"),
tr("password is not the same"));
}else{
QByteArray buffer; //QByteArray类提供了一个字节数组
quint16 blockSize; //quint16 是QT软件下的一种自定义类型,他代表32位计算机中的整型,其功能好比C++/C中的int型
QDataStream out(&buffer,QIODevice::WriteOnly);
out<<(quint16)0<<(quint16)REGISTER<<name<<password;
blockSize=(quint16)(sizeof(buffer)-sizeof(quint16)-sizeof(quint16));
out.device()->seek(0);
out<<blockSize;
client.write(buffer);
}
}
void Widget::goBackToLoginDialog()
{
registerDialog->close();
registerDialog->deleteLater();
loginDialog->show();
client.isRegistering=false;
}
void Widget::closeEvent(QCloseEvent *event)
{
int standardButton=QMessageBox::warning(this,
tr("quit?"),
tr("do you want to leave?"),
QMessageBox::Ok | QMessageBox::Cancel,
QMessageBox::Cancel);
if(standardButton==QMessageBox::Ok){
client.close();
event->accept();
}else{
event->ignore();
}
}
void Widget::tryToConnectToServer()
{
client.setName(loginDialog->numuberEdit->text());
client.setPassword(loginDialog->keyEdit->text());
nameList.clear();
nameList.append(client.name());
nameModel.setStringList(nameList);
ui->nameListView->setModel(&nameModel);
if(client.state()==QAbstractSocket::UnconnectedState){
client.connectToHost(QHostAddress(SERVERADDRESS),SERVERPORT);
if(!client.waitForConnected(3000)){
QMessageBox::warning(registerDialog,
tr("!!!"),
tr("failed to connect"));
}
}else{
client.tellOthersThatICame();
}
}
void Widget::makeConnections()
{
connect(ui->sendPushButton,SIGNAL(clicked()),
this,SLOT(sendMessage()));
connect(&client,SIGNAL(connected()),
this,SLOT(showConnectedInLabel()));
connect(&client,SIGNAL(disconnected()),
this,SLOT(showDisconnectedInLabel()));
connect(&client,SIGNAL(addNewComerToNameList(const QString &,const QHostAddress &)),
this,SLOT(addNewComerToNameList(const QString &,const QHostAddress &)));
connect(&client,SIGNAL(showMessageInTextEdit(const QString &,const QString &,const QString &)),
this,SLOT(showMessageInTextEdit(const QString &,const QString &,const QString &)));
connect(&client,SIGNAL(nameAndPasswordIsRight()),
this,SLOT(nameAndPasswordIsRight()));
connect(&client,SIGNAL(nameAndPasswordIsNotRight()),
this,SLOT(nameAndPasswordIsNotRight()));
connect(&client,SIGNAL(removeLeaverNameFromNameList(const QString &)),
this,SLOT(removeLeaverNameFromNameList(const QString &)));
connect(&client,SIGNAL(registerSuccess()),
this,SLOT(registerSuccess()));
connect(&client,SIGNAL(registerFailed()),
this,SLOT(registerFailed()));
}
void Widget::registerSuccess()
{
QMessageBox::information(registerDialog,
tr("!!!"),
tr("register success"));
goBackToLoginDialog();
}
void Widget::registerFailed()
{
QMessageBox::warning(registerDialog,
tr("!!!"),
tr("name already exist"));
}
void Widget::addNewComerToNameList(const QString &newName,const QHostAddress &address)
{
int row=nameModel.rowCount();
nameModel.insertRow(row);
nameModel.setData(nameModel.index(row),newName,Qt::DisplayRole);
}
void Widget::showMessageInTextEdit(const QString &hisName,const QString ¤tDateTime,const QString &message)
{
ui->showTextEdit->append(QString("\n[%1] %2 %3\n%4")
.arg(currentDateTime)
.arg(hisName)
.arg(QString::fromLocal8Bit("说道:"))
.arg(message) );
}
void Widget::removeLeaverNameFromNameList(const QString &name)
{
for(int i=0;i<nameModel.rowCount();i++){
if(nameModel.data(nameModel.index(i),Qt::DisplayRole)==name){
nameModel.removeRow(i);
}
}
}
void Widget::nameAndPasswordIsNotRight()
{
loginDialog->informationLabel->setText(tr("incorrect password!"));
}
void Widget::nameAndPasswordIsRight()
{
delete loginDialog;
show();
}
void Widget::sendMessage()
{
client.sendMessage(ui->inputTextEdit->toPlainText());
}
Widget::~Widget()
{
}