先来看下效果

再上源代码
头文件
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QCloseEvent>
#include <QApplication>
#include <QDateTime>
class ClientWindow : public QWidget
{
Q_OBJECT
public:
ClientWindow(QWidget *parent = nullptr);
~ClientWindow();
protected:
void closeEvent(QCloseEvent *event) override;
private slots:
void onConnectClicked();
void onDisconnectClicked();
void onSendClicked();
void onConnected();
void onMessageReceived(QString message);
void onDisconnected();
void onExitClicked();
private:
QTcpSocket* socket;
QTextEdit* logEdit;
QLineEdit* inputEdit;
QLineEdit* hostEdit;
QLineEdit* portEdit;
QPushButton* connectButton;
QPushButton* disconnectButton;
};
#endif // CLIENTWINDOW_H
CPP代码
#include "clientwindow.h"
ClientWindow::ClientWindow(QWidget *parent) : QWidget(parent)
{
// 设置窗口属性
setMinimumSize(800, 600);
setFixedSize(800, 600);
//this->setWindowIcon(QIcon(":/new/prefix1/images/tcpserver.ico")); // 需要添加图标资源
// 初始化样式表
QString styleSheet = R"(QWidget{background-color: #f5f5f5;font-family: 'Segoe UI', Arial, sans-serif;}
QTextEdit {background-color: #ffffff;border: 2px solid #1e90ff; border-radius: 8px; padding: 10px; font-size: 14px; color: #333333;selection-background-color: #1e90ff;}
QLineEdit {background-color: #ffffff; border: 2px solid #cccccc; border-radius: 6px; padding: 8px; font-size: 14px; min-height: 20px;}
QLineEdit:focus {border-color: #1e90ff;}
QPushButton {background-color: #1e90ff; color: white; border: none; border-radius: 6px; padding: 10px 20px; font-size: 14px; min-width: 80px;}
QPushButton:hover {background-color: #0066cc;}
QPushButton:disabled { background-color: #cccccc; color: #666666; }
QPushButton#exitButton { background-color: #ff4444; }
QPushButton#exitButton:hover { background-color: #cc0000;} )";
setStyleSheet(styleSheet);
QString styleSheet1 = R"(QLineEdit {background-color: #ffffff;border: 2px solid #cccccc; border-radius: 6px; padding: 8px; font-size: 14px; min-height: 100px; }
QLineEdit:focus { border-color: #1e90ff; })";
// UI组件初始化
hostEdit = new QLineEdit("localhost", this);
portEdit = new QLineEdit("12345", this);
connectButton = new QPushButton("Connect", this);
disconnectButton = new QPushButton("Disconnect", this);
logEdit = new QTextEdit(this);
inputEdit = new QLineEdit(this);
inputEdit->setStyleSheet(styleSheet1);
QPushButton* sendButton = new QPushButton("Send", this);
QPushButton* exitButton = new QPushButton("Exit", this);
exitButton->setObjectName("exitButton");
// 设置组件属性
logEdit->setReadOnly(true);
logEdit->setPlaceholderText("Message log...");
inputEdit->setPlaceholderText("Type your message here...");
portEdit->setFixedWidth(100);
hostEdit->setPlaceholderText("Server address");
portEdit->setPlaceholderText("Port");
disconnectButton->setEnabled(false);
// 布局设置
QVBoxLayout* mainLayout = new QVBoxLayout;
mainLayout->setSpacing(15);
mainLayout->setContentsMargins(20, 20, 20, 20);
// 连接信息布局
QHBoxLayout* connLayout = new QHBoxLayout;
connLayout->addWidget(hostEdit);
connLayout->addWidget(portEdit);
connLayout->addWidget(connectButton);
connLayout->addWidget(disconnectButton);
connLayout->setSpacing(10);
// 按钮布局
QHBoxLayout* buttonLayout = new QHBoxLayout;
buttonLayout->addStretch();
buttonLayout->addWidget(sendButton);
buttonLayout->addWidget(exitButton);
buttonLayout->setSpacing(15);
// 添加所有布局
mainLayout->addLayout(connLayout);
mainLayout->addWidget(logEdit);
mainLayout->addWidget(inputEdit);
mainLayout->addLayout(buttonLayout);
// 设置布局比例
mainLayout->setStretch(0, 0);
// 连接栏
mainLayout->setStretch(1, 1);
// 消息记录(可伸缩)
mainLayout->setStretch(2, 0);
// 输入框
mainLayout->setStretch(3, 0);
// 按钮栏
setLayout(mainLayout);
// 网络组件初始化
socket = new QTcpSocket(this);
// 连接信号槽(保持原有功能不变)
connect(connectButton, &QPushButton::clicked, this, &ClientWindow::onConnectClicked);
connect(disconnectButton, &QPushButton::clicked, this, &ClientWindow::onDisconnectClicked);
connect(sendButton, &QPushButton::clicked, this, &ClientWindow::onSendClicked);
connect(exitButton, &QPushButton::clicked, this, &ClientWindow::onExitClicked);
connect(socket, &QTcpSocket::connected, this, &ClientWindow::onConnected);
connect(socket, &QTcpSocket::disconnected, this, &ClientWindow::onDisconnected);
// connect(socket, QValid of &QTcpSocket::error, this, [this](QAbstractSocket::SocketError)
// {
// logEdit->append("Error: " + socket->errorString());
// }
// )
// ;
connect(socket, &QTcpSocket::readyRead, [this]
{
QByteArray data = socket->readAll();
onMessageReceived(QString::fromUtf8(data));
}
);
}
void ClientWindow::onExitClicked()
{
if (socket->state() != QAbstractSocket::UnconnectedState)
{
socket->abort();
}
qApp->quit(); // 安全退出整个应用程序
}
ClientWindow::~ClientWindow()
{
if (socket->state() != QAbstractSocket::UnconnectedState)
{
socket->abort();
}
}
void ClientWindow::closeEvent(QCloseEvent *event)
{
if (socket->state() != QAbstractSocket::UnconnectedState)
{
socket->abort();
}
event->accept();
}
void ClientWindow::onConnectClicked()
{
bool ok;
int port = portEdit->text().toInt(&ok);
if (!ok)
{
logEdit->append("Invalid port number!");
return;
}
socket->connectToHost(hostEdit->text(), port);
connectButton->setEnabled(false);
disconnectButton->setEnabled(true);
}
void ClientWindow::onDisconnectClicked()
{
if (socket->state() == QAbstractSocket::ConnectedState)
{
socket->disconnectFromHost();
}
connectButton->setEnabled(true);
disconnectButton->setEnabled(false);
}
void ClientWindow::onSendClicked()
{
// 获取当前日期时间
QDateTime currentDateTime = QDateTime::currentDateTime();
// 转换为字符串(格式:yyyy-MM-dd hh:mm:ss)
QString dateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
QString message = inputEdit->text();
if (!message.isEmpty() && socket->state() == QAbstractSocket::ConnectedState)
{
socket->write(message.toUtf8());
logEdit->append("["+dateTimeString+" Me]: "+ message);
inputEdit->clear();
}
}
void ClientWindow::onConnected()
{
logEdit->append("System prompt: Connected to server.");
}
void ClientWindow::onMessageReceived(QString message)
{
// 获取当前日期时间
QDateTime currentDateTime = QDateTime::currentDateTime();
// 转换为字符串(格式:yyyy-MM-dd hh:mm:ss)
QString dateTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
logEdit->append("["+dateTimeString+" Server]: " + message);
}
void ClientWindow::onDisconnected()
{
logEdit->append("System prompt: Disconnected from server.");
connectButton->setEnabled(true);
disconnectButton->setEnabled(false);
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...



