#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget),m_pTcpSock(NULL)
{
ui->setupUi(this);
ui->Line_ip->setText("127.0.0.1");
ui->Line_Port->setText("8888");
ui->Line_Send->setDisabled(true);
ui->Button_Send->setDisabled(true);
m_pTcpSock = new QTcpSocket(this);
connect(m_pTcpSock,&QTcpSocket::connected,this,&Widget::on_connect_suc);
connect(m_pTcpSock,&QTcpSocket::readyRead,this,&Widget::on_recv_read);
connect(m_pTcpSock,&QTcpSocket::disconnected,this,&Widget::on_connect_end);
//ui->List_Context->
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_Button_Connect_clicked()
{
if(QString("链接") == ui->Button_Connect->text()){
str_usr = ui->Line_Usr->text();
QString str_ip = ui->Line_ip->text();
QString str_port = ui->Line_Port->text();
if(QString("") == str_usr || QString("") == str_ip || QString("") == str_port){
return;
}
QHostAddress addr;
addr.setAddress(str_ip);
m_pTcpSock->connectToHost(addr,str_port.toUInt());
//ui->Button_Connect->setText("断开");
}else{
//ui->Button_Connect->setText("链接");
QString strtmp = str_usr + "退出聊天室";
m_pTcpSock->write(strtmp.toLocal8Bit());
//断开
m_pTcpSock->disconnectFromHost();
}
}
void Widget::on_Button_Send_clicked()
{
QString strtmp = str_usr+ ":"+ui->Line_Send->text();
m_pTcpSock->write(strtmp.toLocal8Bit());
ui->Line_Send->clear();
}
void Widget::on_connect_suc()
{
ui->Button_Connect->setText("断开");
QString strtmp = str_usr + "进入聊天室";
m_pTcpSock->write(strtmp.toLocal8Bit());
ui->Line_Send->setDisabled(false);
ui->Button_Send->setDisabled(false);
ui->Line_Usr->setDisabled(true);
ui->Line_ip->setDisabled(true);
ui->Line_Port->setDisabled(true);
}
void Widget::on_recv_read()
{
QByteArray byte_str = m_pTcpSock->readAll();
QString str_tmp = QString::fromLocal8Bit(byte_str);
ui->List_Context->addItem(str_tmp);
ui->List_Context->setCurrentRow(ui->List_Context->count());
if(0 == str_tmp.indexOf(str_usr+ ":")){
str_tmp.remove(str_usr+ ":");
str_tmp+= ":"+str_usr;
QListWidgetItem* pitem = ui->List_Context->item(ui->List_Context->count()-1);
if(NULL != pitem){
pitem->setText(str_tmp);
pitem->setTextAlignment(Qt::AlignRight);
//ui->List_Context.modi
}
}else if(str_tmp.size()-5 == str_tmp.lastIndexOf("进入聊天室")
|| str_tmp.size()-5 == str_tmp.lastIndexOf("退出聊天室")){
str_tmp.remove(str_usr+ ":");
str_tmp+= ":"+str_usr;
QListWidgetItem* pitem = ui->List_Context->item(ui->List_Context->count()-1);
if(NULL != pitem){
//pitem->setText(str_tmp);
pitem->setTextAlignment(Qt::AlignCenter);
//ui->List_Context.modi
}
}else{;}
}
void Widget::on_connect_end()
{
ui->Button_Connect->setText("链接");
ui->Line_Send->setDisabled(true);
ui->Button_Send->setDisabled(true);
ui->Line_Usr->setDisabled(false);
ui->Line_ip->setDisabled(false);
ui->Line_Port->setDisabled(false);
}
思维导图