最近在做网络编程实验,要求用到图形界面,于是又重拾了QT这个非常喜欢的C++框架。在QT官网上找到了一个特别容易上手的小软件,在此和大家一起分享,并加强一下对QT的应用。
这是代码的网址
最后软件的样子,接下来就一段代码一段代码的分析。
首先是工程
</pre>HEADERS = chatdialog.h \ client.h \ connection.h \ peermanager.h \ server.hSOURCES = chatdialog.cpp \ client.cpp \ connection.cpp \ main.cpp \ peermanager.cpp \ server.cppFORMS = chatdialog.uiQT += network widgets# installtarget.path = $$[QT_INSTALL_EXAMPLES]/network/network-chatINSTALLS += target 和普通的qmake文件没什么太大区别,注意要加上 QT += network widgets ,只有加上这个QT 才能有网络库。接下来是整个界面的定义,Chatdialog.h#ifndef CHATDIALOG_H#define CHATDIALOG_H#include "ui_chatdialog.h"#include "client.h"class ChatDialog : public QDialog, private Ui::ChatDialog{ Q_OBJECTpublic: ChatDialog(QWidget *parent = 0);public slots: void appendMessage(const QString &from, const QString &message);private slots: void returnPressed(); void newParticipant(const QString &nick); void participantLeft(const QString &nick); void showInformation();private: Client client; QString myNickName; QTextTableFormat tableFormat;};#endif然后是界面的实现Chatdialog.cpp#include <QtWidgets>#include "chatdialog.h"ChatDialog::ChatDialog(QWidget *parent) : QDialog(parent){ setupUi(this); lineEdit->setFocusPolicy(Qt::StrongFocus); //将光标锁定在lineEdit textEdit->setFocusPolicy(Qt::NoFocus); //光标不会出现在textedit,listwidget textEdit->setReadOnly(true); listWidget->setFocusPolicy(Qt::NoFocus); connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed())); connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed())); connect(&client, SIGNAL(newMessage(QString,QString)), this, SLOT(appendMessage(QString,QString))); connect(&client, SIGNAL(newParticipant(QString)), this, SLOT(newParticipant(QString))); connect(&client, SIGNAL(participantLeft(QString)), this, SLOT(participantLeft(QString))); myNickName = client.nickName(); //返回用户名,nickName()是自己定义的一个函数 newParticipant(myNickName); tableFormat.setBorder(0); //设置界面边沿宽度为0 QTimer::singleShot(10 * 1000, this, SLOT(showInformation()));//程序在10秒后会调用一个槽showInformation() }void ChatDialog::appendMessage(const QString &from, const QString &message){ if (from.isEmpty() || message.isEmpty()) return; QTextCursor cursor(textEdit->textCursor()); cursor.movePosition(QTextCursor::End); //将textEdit里的光标设置在文字的最后,以免输出混乱 QTextTable *table = cursor.insertTable(1, 2, tableFormat); table->cellAt(0, 0).firstCursorPosition().insertText('<' + from + "> ");table->cellAt(0, 1).firstCursorPosition().insertText(message); //设置textEdit的输出格式 QScrollBar *bar = textEdit->verticalScrollBar();//设置textEdit支持垂直滚动 bar->setValue(bar->maximum());}void ChatDialog::returnPressed(){ QString text = lineEdit->text(); if (text.isEmpty()) return; if (text.startsWith(QChar('/'))) { //输入以"/"打头的字符会报错 QColor color = textEdit->textColor(); textEdit->setTextColor(Qt::red); //报错内容为红色 textEdit->append(tr("! Unknown command: %1") .arg(text.left(text.indexOf(' ')))); textEdit->setTextColor(color); //将输出内容重新设为黑色 } else { client.sendMessage(text); //发送给客户机文本信息 appendMessage(myNickName, text); //在本机上显示文本信息 } lineEdit->clear();}void ChatDialog::newParticipant(const QString &nick){ if (nick.isEmpty()) return; QColor color = textEdit->textColor(); textEdit->setTextColor(Qt::gray); //将加入者信息输出设为灰色 textEdit->append(tr("* %1 has joined").arg(nick)); textEdit->setTextColor(color); /重设为黑色 listWidget->addItem(nick); //在listWidget栏内添加新的成员 }void ChatDialog::participantLeft(const QString &nick){ if (nick.isEmpty()) return; QList<QListWidgetItem *> items = listWidget->findItems(nick, Qt::MatchExactly); //在listWidget栏中找到离开者的项 if (items.isEmpty()) return; delete items.at(0); //删除项 QColor color = textEdit->textColor(); textEdit->setTextColor(Qt::gray); textEdit->append(tr("* %1 has left").arg(nick)); //输出相应信息 textEdit->setTextColor(color);}void ChatDialog::showInformation() //十秒后输出的信息 { if (listWidget->count() == 1) { QMessageBox::information(this, tr("Chat"), tr("Launch several instances of this " "program on your local network and " "start chatting!")); }}接下来是客户机的定义:Client.h#ifndef CLIENT_H#define CLIENT_H#include <QAbstractSocket>#include <QHash>#include <QHostAddress>#include "server.h"class PeerManager;class Client : public QObject{ Q_OBJECTpublic: Client(); void sendMessage(const QString &message); QString nickName() const; bool hasConnection(const QHostAddress &senderIp