以下是一个简单的基于Qt实现的IM系统的代码示例:
// main.cpp
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTcpSocket>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_connectButton_clicked();
void on_sendButton_clicked();
void socketConnected();
void socketDisconnected();
void socketReadyRead();
private:
Ui::MainWindow *ui;
QTcpSocket *socket;
};
#endif // MAINWINDOW_H
// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
socket(nullptr)
{
ui->setupUi(this);
// 初始化socket对象并连接相关信号槽
socket = new QTcpSocket(this);
connect(socket, &QTcpSocket::connected, this, &MainWindow::socketConnected);
connect(socket, &QTcpSocket::disconnected, this, &MainWindow::socketDisconnected);
connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socketReadyRead);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_connectButton_clicked() {
QString serverAddress = ui->serverLineEdit->text();
int port = ui->portLineEdit->text().toInt();
// 连接到指定服务器地址和端口
socket->connectToHost(serverAddress, port);
}
void MainWindow::on_sendButton_clicked() {
QString message = ui->messageLineEdit->text();
// 发送消息到服务器
socket->write(message.toUtf8());
}
void MainWindow::socketConnected() {
ui->statusLabel->setText("Connected");
}
void MainWindow::socketDisconnected() {
ui->statusLabel->setText("Disconnected");
}
void MainWindow::socketReadyRead() {
QByteArray data = socket->readAll();
// 处理接收到的数据
ui->chatTextEdit->append(data);
}
这只是一个简单的示例,实际的IM系统还需要更多功能和错误处理。请注意,在使用此代码之前,您需要创建一个Qt Widgets应用程序,并在MainWindow类中添加相应的UI元素。
内容由零声教学AI助手提供,问题来源于学员提问