2024-02-08 QT work

本文介绍了如何使用QT库创建一个简单的QQ登录界面,包括连接服务器、发送用户名信息、接收并显示服务器消息以及断开连接的功能。
摘要由CSDN通过智能技术生成

1. 使用QT编写一个简单QQ登录界面

#include "mywidget.h"
#include "mywidget.h"
#include "ui_mywidget.h"

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MyWidget)
{
    ui->setupUi(this);

    //指针初始化
    socket = new QTcpSocket(this);
    //初始化按钮不可用
    ui->messageEdit->setEnabled(false);
    ui->sendButton->setEnabled(false);
    ui->exitButton->setEnabled(false);

    connect(socket,&QTcpSocket::connected,this,&MyWidget::my_connectslot);

    connect(socket,&QTcpSocket::readyRead,this,&MyWidget::my_readyReadSlot);

    connect(socket,&QTcpSocket::disconnected,this,&MyWidget::my_disconnectSlot);

}

MyWidget::~MyWidget()
{
    delete ui;
}

//连接服务器槽函数
void MyWidget::on_connectButton_clicked()
{
    ip = ui->ipEdit->text();
    port = ui->portEdit->text().toUInt();

    socket->connectToHost(ip,port);
    //如果客户端和服务器成功连接,会发送connected信号
}

void MyWidget::my_connectslot()
{
    //连接成功提示信息
    QMessageBox::information(this,"提示","连接服务器成功");
    //告诉服务器上线
    userName = ui->userNameEdit->text();
    QString message = userName +": 进入聊天室";
    //发送消息给服务器
    socket->write(message.toLocal8Bit());

    //设置ui界面,如下三个可用
    ui->messageEdit->setEnabled(true);
    ui->sendButton->setEnabled(true);
    ui->exitButton->setEnabled(true);

    ui->userNameEdit->setEnabled(false);
    ui->ipEdit->setEnabled(false);
    ui->portEdit->setEnabled(false);
    ui->connectButton->setEnabled(false);

    //会发送接收服务器消息的信息,由于只是连接一次,所以写在构造函数中

}

void MyWidget::my_readyReadSlot()
{
    QByteArray array =  socket->readAll();
    //读取服务器的消息,显示在页面上
    ui->messageWidget->addItem(QString::fromLocal8Bit(array));
}

//断开连接,槽函数处理
void MyWidget::my_disconnectSlot()
{
    QMessageBox::information(this,"提示","断开连接成功");
    //给服务器发送断开连接消息
    ui->messageEdit->setEnabled(false);
    ui->sendButton->setEnabled(false);
    ui->exitButton->setEnabled(false);

    ui->userNameEdit->setEnabled(true);
    ui->ipEdit->setEnabled(true);
    ui->portEdit->setEnabled(true);
    ui->connectButton->setEnabled(true);

}

//发送消息给服务器
void MyWidget::on_sendButton_clicked()
{
    //获取文本内容
    QString message = userName + ": " + ui->messageEdit->text();
    socket->write(message.toLocal8Bit());
    //清空输入文本框
    ui->messageEdit->clear();
}

//断开连接按钮,对应的槽函数
void MyWidget::on_exitButton_clicked()
{
    //退出,断开与服务器的连接
    qDebug() << "客户端与服务器断开连接";
    //断开之前提示某某离开
    QString message = userName +": " +"离开聊天室";
    socket->write(message.toLocal8Bit());
    socket->disconnectFromHost();
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值