使用绘制事件完成钟表的绘制
头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTcpSocket>
#include<QMessageBox>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_connectBtn_clicked();
void connected_slot();
void readyRead_slot();
void on_sendBtn_clicked();
void on_disConnectBtn_clicked();
void disconnected_slot();
private:
Ui::Widget *ui;
QTcpSocket *client;
QString userName;
};
#endif // WIDGET_H
源文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//实例化客户端对象
client = new QTcpSocket(this);
connect(client,&QTcpSocket::connected,this,&Widget::connected_slot);
connect(client,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
connect(client,&QTcpSocket::disconnected,this,&Widget::disconnected_slot);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_connectBtn_clicked()
{
//获取ui界面上的数据
QString ip = ui->ipEdit->text();
quint16 port = ui->portEdit->text().toUInt();
userName = ui->nameEdit->text();
//调用套接字成员函数,连接服务器
client->connectToHost(ip,port);
}
void Widget::connected_slot()
{
QMessageBox::information(this,"成功","连接成功");
ui->ipEdit->setEnabled(false);
ui->nameEdit->setEnabled(false);
ui->portEdit->setEnabled(false);
ui->connectBtn->setEnabled(false);
QString msg = userName + ":Ciallo~(∠·ω<)⌒☆";
client->write(msg.toLocal8Bit());
}
void Widget::readyRead_slot()
{
//从套接字中读取数据
QByteArray msg = client->readAll();
//将读取下来的数据展示到ui界面上
ui->msglistWidget->addItem(QString::fromLocal8Bit(msg));
}
//消息发送
void Widget::on_sendBtn_clicked()
{
//组织要发送的消息
QString msg = userName + ":" + ui->msgEdit->text();
//将消息发送给服务器
client->write(msg.toLocal8Bit());
//将消息展示到自己的界面上
QListWidgetItem *item = new QListWidgetItem(msg);
item->setTextAlignment(Qt::AlignRight);
ui->msglistWidget->addItem(item);
//清空消息发送框的内容
ui->msgEdit->clear();
}
//断开连接
void Widget::on_disConnectBtn_clicked()
{
QString msg = userName + ":离开聊天室";
client->write(msg.toLocal8Bit());
//断开连接
client->disconnectFromHost();
}
void Widget::disconnected_slot()
{
QMessageBox::information(this,"提示","成功断开连接");
ui->ipEdit->setEnabled(true);
ui->nameEdit->setEnabled(true);
ui->portEdit->setEnabled(true);
ui->connectBtn->setEnabled(true);
}