第七章:Qt 实践

ops/2025/3/13 17:29:36/

第七章:Qt 实践

在深入了解 Qt 框架的各个模块之后,本章将通过几个实际案例,展示如何将 Qt 的强大功能应用于真实项目开发中。我们将结合界面设计、信号与槽机制、网络通信和数据处理等内容,探索 Qt 在桌面应用程序开发中的实际应用。


7.1 案例一:简单的文本编辑器
7.1.1 项目目标

构建一个支持文本编辑、保存和打开文件的简易文本编辑器,学习 QMainWindow、菜单栏和文件操作的使用。

7.1.2 主要功能
  • 打开文件: 通过文件对话框选择文件并加载内容。
  • 保存文件: 将编辑内容写入到文件。
  • 编辑功能: 提供基本的文本编辑功能。
7.1.3 核心代码
#include <QApplication>
#include <QMainWindow>
#include <QTextEdit>
#include <QMenuBar>
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>class TextEditor : public QMainWindow {Q_OBJECT
private:QTextEdit *editor;public:TextEditor() {editor = new QTextEdit(this);setCentralWidget(editor);QMenu *fileMenu = menuBar()->addMenu("File");QAction *openAction = fileMenu->addAction("Open");QAction *saveAction = fileMenu->addAction("Save");QAction *exitAction = fileMenu->addAction("Exit");connect(openAction, &QAction::triggered, this, &TextEditor::openFile);connect(saveAction, &QAction::triggered, this, &TextEditor::saveFile);connect(exitAction, &QAction::triggered, this, &QMainWindow::close);}private slots:void openFile() {QString fileName = QFileDialog::getOpenFileName(this, "Open File");if (fileName.isEmpty()) return;QFile file(fileName);if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {QMessageBox::warning(this, "Error", "Could not open file");return;}QTextStream in(&file);editor->setText(in.readAll());file.close();}void saveFile() {QString fileName = QFileDialog::getSaveFileName(this, "Save File");if (fileName.isEmpty()) return;QFile file(fileName);if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {QMessageBox::warning(this, "Error", "Could not save file");return;}QTextStream out(&file);out << editor->toPlainText();file.close();}
};int main(int argc, char *argv[]) {QApplication app(argc, argv);TextEditor editor;editor.setWindowTitle("Simple Text Editor");editor.resize(800, 600);editor.show();return app.exec();
}
7.1.4 功能亮点
  • 使用 QTextEdit 提供文本编辑功能。
  • 文件打开和保存通过 QFileDialogQFile 实现。
  • 菜单栏通过 QMenuBarQAction 构建。

7.2 案例二:网络聊天应用
7.2.1 项目目标

构建一个局域网内实时聊天应用,学习使用 QTcpServerQTcpSocket 进行通信。

7.2.2 主要功能
  • 服务器端: 接收并转发客户端消息。
  • 客户端: 连接服务器并发送消息。
7.2.3 核心代码
服务器端
#include <QApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>class ChatServer : public QTcpServer {Q_OBJECT
private:QList<QTcpSocket *> clients;protected:void incomingConnection(qintptr socketDescriptor) override {QTcpSocket *client = new QTcpSocket(this);client->setSocketDescriptor(socketDescriptor);clients << client;connect(client, &QTcpSocket::readyRead, [=]() {QByteArray data = client->readAll();for (QTcpSocket *other : clients) {if (other != client) other->write(data);}});connect(client, &QTcpSocket::disconnected, [=]() {clients.removeAll(client);client->deleteLater();});}
};int main(int argc, char *argv[]) {QApplication app(argc, argv);ChatServer server;if (server.listen(QHostAddress::Any, 12345)) {qDebug() << "Server is running on port 12345";} else {qDebug() << "Server failed to start";}return app.exec();
}
客户端
#include <QApplication>
#include <QTcpSocket>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QTextBrowser>
#include <QPushButton>class ChatClient : public QWidget {Q_OBJECT
private:QTcpSocket *socket;QTextBrowser *chatDisplay;QLineEdit *messageInput;public:ChatClient() {socket = new QTcpSocket(this);chatDisplay = new QTextBrowser(this);messageInput = new QLineEdit(this);QPushButton *sendButton = new QPushButton("Send", this);QVBoxLayout *layout = new QVBoxLayout(this);layout->addWidget(chatDisplay);layout->addWidget(messageInput);layout->addWidget(sendButton);connect(sendButton, &QPushButton::clicked, this, &ChatClient::sendMessage);connect(socket, &QTcpSocket::readyRead, this, &ChatClient::receiveMessage);socket->connectToHost("127.0.0.1", 12345);}private slots:void sendMessage() {QString message = messageInput->text();if (!message.isEmpty()) {socket->write(message.toUtf8());messageInput->clear();}}void receiveMessage() {QByteArray data = socket->readAll();chatDisplay->append(QString::fromUtf8(data));}
};int main(int argc, char *argv[]) {QApplication app(argc, argv);ChatClient client;client.setWindowTitle("Chat Client");client.resize(400, 300);client.show();return app.exec();
}
7.2.4 功能亮点
  • 服务器端管理多个客户端连接,支持消息广播。
  • 客户端实现简单的聊天界面,通过信号槽实现消息收发。

7.3 案例三:图片浏览器
7.3.1 项目目标

开发一个简单的图片浏览器,支持加载本地图片文件并显示,学习 QGraphicsView 的使用。

7.3.2 核心代码
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QFileDialog>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>class ImageViewer : public QWidget {Q_OBJECT
private:QGraphicsView *view;QGraphicsScene *scene;public:ImageViewer() {view = new QGraphicsView(this);scene = new QGraphicsScene(this);view->setScene(scene);QPushButton *loadButton = new QPushButton("Load Image", this);QVBoxLayout *layout = new QVBoxLayout(this);layout->addWidget(view);layout->addWidget(loadButton);connect(loadButton, &QPushButton::clicked, this, &ImageViewer::loadImage);}private slots:void loadImage() {QString fileName = QFileDialog::getOpenFileName(this, "Open Image", "", "Images (*.png *.jpg *.bmp)");if (!fileName.isEmpty()) {scene->clear();QPixmap pixmap(fileName);scene->addPixmap(pixmap);view->fitInView(scene->itemsBoundingRect(), Qt::KeepAspectRatio);}}
};int main(int argc, char *argv[]) {QApplication app(argc, argv);ImageViewer viewer;viewer.setWindowTitle("Image Viewer");viewer.resize(800, 600);viewer.show();return app.exec();
}
7.3.3 功能亮点
  • 使用 QGraphicsViewQGraphicsScene 显示图片。
  • 提供简单的文件加载功能。

7.4 小结

本章通过多个案例展示了 Qt 在实际开发中的应用,包括文本编辑器、网络聊天应用和图片浏览器。这些项目涵盖了 Qt 的多个模块和技术,帮助开发者将理论知识转化为实践能力。


http://www.ppmy.cn/ops/165461.html

相关文章

力扣:3305.元音辅音字符串计数

给你一个字符串 word 和一个 非负 整数 k。 返回 word 的 子字符串 中&#xff0c;每个元音字母&#xff08;a、e、i、o、u&#xff09;至少 出现一次&#xff0c;并且 恰好 包含 k 个辅音字母的子字符串的总数。 示例 1&#xff1a; 输入&#xff1a;word "aeioqq"…

MySQL中IN关键字与EXIST关键字的比较

文章目录 **功能等价性分析****执行计划分析**&#xff1a; **1. EXISTS 的工作原理****步骤拆解**&#xff1a; **2. 为什么需要“利用索引快速定位”&#xff1f;****索引作用示例**&#xff1a; **3. 与 IN 子查询的对比****IN 的工作方式**&#xff1a;**关键差异**&#x…

Hack Me Please: 1靶场渗透测试

Hack Me Please: 1 来自 <https://www.vulnhub.com/entry/hack-me-please-1,731/> 1&#xff0c;将两台虚拟机网络连接都改为NAT模式 2&#xff0c;攻击机上做namp局域网扫描发现靶机 nmap -sn 192.168.23.0/24 那么攻击机IP为192.168.23.182&#xff0c;靶场IP192.168.…

Linux_17进程控制

前提回顾&#xff1a; 页表可以将无序的物理地址映射为有序的; 通过进程地址空间&#xff0c;避免将内存直接暴漏给操作系统&#xff1b; cr3寄存器存放的有当前运行进程的页表的物理地址&#xff1b; 一、查看命令行参数和环境变量的地址 因为命令行参数和环境变量都是字符…

[从零开始学习JAVA] 新版本idea的数据库图形化界面

前言: 在看黑马javaweb的时候&#xff0c;发现视频中的版本是老版本,而我的是新版本 为了记录新版本的数据库界面图形化操作我打算写下这篇博客 案例 创建tb_user表 对应的结构如下 要求 1.id 是一行数据的唯一标识 2.username 用户名字段是非空且唯一的 3.name 姓名字…

Javascript ajax

9.1 学习ajax的前置知识——JSON JSON是什么 JSON(JavaScript Object Notation)是⼀种轻量级的数据交换格式&#xff0c;它基于JavaScript的⼀个⼦集&#xff0c;易于⼈的编写和阅读&#xff0c;也易于机器解析。 JSON采⽤完全独⽴于语⾔的⽂本格式&#xff0c;但是也使⽤了类似…

宇树人形机器人开源模型

1. 下载源码 https://github.com/unitreerobotics/unitree_ros.git2. 启动Gazebo roslaunch h1_description gazebo.launch3. 仿真效果 H1 GO2 B2 Laikago Z1 4. VMware: vmw_ioctl_command error Invalid argument 这个错误通常出现在虚拟机环境中运行需要OpenGL支持的应用…

iOS UICollectionViewCell 点击事件自动化埋点

iOS 中经常要进行埋点&#xff0c;我们这里支持 UICollectionViewCell. 进行自动化埋点&#xff0c;思路&#xff1a; 通过hook UICollectionViewCell 的setSelected:方法&#xff0c; 则新的方法中执行埋点逻辑&#xff0c;并调用原来的方法 直接上代码 implementation UICol…