编程进阶网 编程进阶网
首页
  • 计算机原理
  • 操作系统
  • 网络协议
  • 数据库原理
  • 面向对象
  • 设计原则
  • 设计模式
  • 系统架构
  • 性能优化
  • 编程原理
  • 方案设计
  • 稳定可靠
  • 工程运维
  • 基础认知
  • 线性结构
  • 树与哈希
  • 工业级实现
  • 算法思想
  • 实战与综合
  • 算法题考核
  • C语言入门
  • C综合案例
  • C专栏博客
  • C标准集库
  • C++入门教程
  • C++综合案例
  • C++专栏博客
  • C++开发技巧
  • Java入门教程
  • Java综合案例
  • Java专栏博客
  • Go入门教程
  • Go综合案例
  • Go专栏博客
  • Go开发技巧
  • JavaScript入门
  • JavaScript高级
  • Android库解读
  • Android专栏
  • Android智能硬件
  • iOS ObjC入门
  • iOS Swift入门
  • iOS入门精通
  • Web之Html手册
  • Web之TypeScript
  • Web之Vue高级进阶
  • Linux之QML入门
  • Linux之QT核心库
  • Linux实践开发
  • Python教程
  • Shell&Bash教程
  • 工具脚本
  • 自动化脚本
  • 质量保障
  • 产品思考
  • 软实力
  • 开发流程
  • Git应用
  • 技术模版
  • 技术规范
  • Markdown
  • Mermaid
  • 开源协议
  • JSON工具
  • 文本工具
  • 图片处理
  • 文档转化
  • 代码压缩
  • 关于我
  • 自我精进
  • 职场管理
  • 职场面试
  • 心情杂货
  • 友情链接

杨充

专注编程 · 终身学习者
首页
  • 计算机原理
  • 操作系统
  • 网络协议
  • 数据库原理
  • 面向对象
  • 设计原则
  • 设计模式
  • 系统架构
  • 性能优化
  • 编程原理
  • 方案设计
  • 稳定可靠
  • 工程运维
  • 基础认知
  • 线性结构
  • 树与哈希
  • 工业级实现
  • 算法思想
  • 实战与综合
  • 算法题考核
  • C语言入门
  • C综合案例
  • C专栏博客
  • C标准集库
  • C++入门教程
  • C++综合案例
  • C++专栏博客
  • C++开发技巧
  • Java入门教程
  • Java综合案例
  • Java专栏博客
  • Go入门教程
  • Go综合案例
  • Go专栏博客
  • Go开发技巧
  • JavaScript入门
  • JavaScript高级
  • Android库解读
  • Android专栏
  • Android智能硬件
  • iOS ObjC入门
  • iOS Swift入门
  • iOS入门精通
  • Web之Html手册
  • Web之TypeScript
  • Web之Vue高级进阶
  • Linux之QML入门
  • Linux之QT核心库
  • Linux实践开发
  • Python教程
  • Shell&Bash教程
  • 工具脚本
  • 自动化脚本
  • 质量保障
  • 产品思考
  • 软实力
  • 开发流程
  • Git应用
  • 技术模版
  • 技术规范
  • Markdown
  • Mermaid
  • 开源协议
  • JSON工具
  • 文本工具
  • 图片处理
  • 文档转化
  • 代码压缩
  • 关于我
  • 自我精进
  • 职场管理
  • 职场面试
  • 心情杂货
  • 友情链接
  • README
  • Android提升进阶

  • iOS开发和进阶

  • Web开发和进阶

  • Linux应用开发

    • README
    • QML基础入门

    • QT核心库实践

      • README
      • 核心功能基础
      • 并发与多线程
      • 文件与IO系统
      • 日期与时间处理
      • 网络与序列化
      • QT事件系统
      • 信号与槽机制
      • 多媒体的应用
      • 容器类和算法
      • 高级编程技巧
        • 10.1 QProcess进程
          • 10.1.1 启动外部进程
          • 10.1.2 异步读取输出
          • 10.1.3 发送输入到进程
          • 10.1.4 获取进程状态
          • 10.1.5 常用的信号
          • 10.1.6 如何终止进程
          • 10.1.7 QProcess总结
        • 10.2 进程环境变量
          • 10.2.1 设置环境变量
          • 10.2.2 获取系统环境变量
          • 10.2.3 清空环境变量
        • 七、插件系统
          • 1. 插件框架
        • 八、工具类与算法
          • 1. 实用工具
          • 2. 算法与函数式编程
        • 九、国际化与本地化
          • 1. 多语言支持
        • 十、内存管理
          • 1. 智能指针
          • 2. 对象生命周期
        • 十二、系统集成
          • 1. 平台抽象
          • 2. 进程管理
        • 十三、设计模式实现
          • 1. 常用模式
        • 十四、性能分析工具
          • 1. 性能工具
          • 1. 插件框架的基本概念
          • 2. 创建插件
          • (1)定义接口
          • (2)实现插件
          • (3)编译插件
          • 3. 加载插件
          • (1)使用 `QPluginLoader` 加载插件
          • (2)处理插件加载失败
          • 4. 插件的动态加载与卸载
          • 5. 插件的元数据
          • 6. 插件的搜索路径
          • 7. 插件的多平台支持
          • 8. 完整示例
          • (1)插件接口
          • (2)插件实现
          • (3)加载插件
          • 总结
          • 1. QVariant:通用类型容器
          • (1)基本用法
          • (2)存储复杂类型
          • 2. QDebug:调试输出
          • (1)基本用法
          • (2)禁用调试输出
          • 3. QRandomGenerator:随机数生成
          • (1)基本用法
          • (2)生成随机字符串
          • 4. QCommandLineParser:命令行参数解析
          • (1)基本用法
          • (2)运行示例
          • 总结
          • 1. QtAlgorithms:基本算法
          • (1)弃用说明
          • (2)示例:使用 STL 替代 `QtAlgorithms`
          • 2. QtConcurrent:并行计算框架
          • (1)基本用法
          • (2)并行过滤
          • (3)并行映射-归约
          • 3. QScopeGuard:作用域守卫(Qt 6)
          • (1)基本用法
          • (2)禁用作用域守卫
          • 总结
    • Linux实践开发

  • Apps
  • Linux应用开发
  • QT核心库实践
杨充
2025-08-22
目录

高级编程技巧

# 目录介绍

  • 10.1 QProcess进程
    • 10.1.1 启动外部进程
    • 10.1.2 异步读取输出
    • 10.1.3 发送输入到进程
    • 10.1.4 获取进程状态
    • 10.1.5 常用的信号
    • 10.1.6 如何终止进程
    • 10.1.7 QProcess总结
  • 10.2 进程环境变量
    • 10.2.1 设置环境变量
    • 10.2.2 获取系统环境变量
    • 10.2.3 清空环境变量

# 10.1 QProcess进程

QProcess 是 Qt 中用于启动和控制外部进程的类。它允许你运行系统命令、与其他程序交互,并获取其输出和错误信息。

QProcess 是跨平台的,适用于 Windows、macOS 和 Linux 等操作系统。

# 10.1.1 启动外部进程

使用 start() 方法启动外部进程。

#include <QProcess>
#include <QDebug>

int main() {
    QProcess process;
    process.start("ls", QStringList() << "-l" << "/"); // 启动 ls -l / 命令
    if (process.waitForStarted()) {
        qDebug() << "Process started.";
    } else {
        qDebug() << "Failed to start process:" << process.errorString();
        return 1;
    }
    // 等待进程结束
    if (process.waitForFinished()) {
        qDebug() << "Process finished.";
        QByteArray output = process.readAllStandardOutput(); // 读取标准输出
        qDebug() << "Output:" << output;
    } else {
        qDebug() << "Process failed:" << process.errorString();
    }
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

启动带参数的命令,可以通过 QStringList 传递命令行参数。

QProcess process;
process.start("echo", QStringList() << "Hello, Qt!");
process.waitForFinished();
qDebug() << "Output:" << process.readAllStandardOutput();
1
2
3
4

# 10.1.2 异步读取输出

使用 readAllStandardOutput() 读取进程的标准输出。

#include <QProcess>
#include <QDebug>

int main() {
    QProcess process;
    QObject::connect(&process, &QProcess::readyReadStandardOutput, [&]() {
        QByteArray output = process.readAllStandardOutput();
        qDebug() << "Output:" << output;
    });
    process.start("ping", QStringList() << "google.com");
    if (process.waitForStarted()) {
        qDebug() << "Process started.";
    } else {
        qDebug() << "Failed to start process:" << process.errorString();
        return 1;
    }
    // 等待进程结束
    process.waitForFinished();
    qDebug() << "Process finished.";
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

使用 readAllStandardError() 读取进程的标准错误。

QString error = process.readAllStandardError();
qDebug() << "Error:" << error;
1
2

# 10.1.3 发送输入到进程

#include <QProcess>
#include <QDebug>

int main() {
    QProcess process;
    process.start("grep", QStringList() << "hello");
    if (process.waitForStarted()) {
        qDebug() << "Process started.";
        process.write("hello world\n"); // 发送输入
        process.closeWriteChannel(); // 关闭输入通道
    } else {
        qDebug() << "Failed to start process:" << process.errorString();
        return 1;
    }
    // 等待进程结束
    if (process.waitForFinished()) {
        qDebug() << "Process finished.";
        QByteArray output = process.readAllStandardOutput();
        qDebug() << "Output:" << output;
    } else {
        qDebug() << "Process failed:" << process.errorString();
    }
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 10.1.4 获取进程状态

使用 state() 检查进程的当前状态。

#include <QProcess>
#include <QDebug>

int main() {
    QProcess process;
    process.start("sleep", QStringList() << "5");
    while (process.state() == QProcess::Running) {
        qDebug() << "Process is running...";
        QThread::sleep(1);
    }
    qDebug() << "Process finished with exit code:" << process.exitCode();
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 10.1.5 常用的信号

QProcess 提供了多个信号,可以用于异步处理进程的输出和状态。

  • readyReadStandardOutput():当有标准输出时触发。
  • readyReadStandardError():当有标准错误时触发。
  • finished(int exitCode, QProcess::ExitStatus status):当进程结束时触发。
  • errorOccurred(QProcess::ProcessError error):当进程发生错误时触发。

# 10.1.6 如何终止进程

使用 kill() 或 terminate() 终止进程。

QProcess process;
process.start("sleep", QStringList() << "10");
process.waitForStarted();

process.kill(); // 强制终止
// process.terminate(); // 尝试优雅终止
1
2
3
4
5
6

# 10.1.7 QProcess总结

  • 启动进程:使用 start() 启动外部进程。
  • 获取输出:使用 readAllStandardOutput() 和 readAllStandardError() 获取进程输出。
  • 异步处理:通过信号与槽机制处理进程的输出和状态。
  • 进程控制:使用 kill() 或 terminate() 终止进程。
  • 环境变量:使用 setProcessEnvironment() 设置环境变量。
  • 输入输出重定向:使用 write() 和 setStandardOutputFile() 重定向输入输出。

# 10.2 进程环境变量

QProcessEnvironment:用于管理进程的环境变量,支持添加、修改和删除环境变量。

# 10.2.1 设置环境变量

使用 setProcessEnvironment() 设置进程的环境变量。

QProcess process;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
// 添加或修改环境变量
env.insert("MY_VAR", "Hello, Qt!");
// 设置进程的环境变量
process.setProcessEnvironment(env);
// 启动进程
process.start("printenv", QStringList() << "MY_VAR");
if (process.waitForFinished()) {
    QByteArray output = process.readAllStandardOutput();
    qDebug() << "Output:" << output;
} else {
    qDebug() << "Process failed:" << process.errorString();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 10.2.2 获取系统环境变量

#include <QProcessEnvironment>
#include <QDebug>

int main(){
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    // 获取 PATH 环境变量
    QString path = env.value("PATH");
    qDebug() << "PATH:" << path;
    return 0;
}
1
2
3
4
5
6
7
8
9
10

# 10.2.3 清空环境变量

#include <QProcess>
#include <QProcessEnvironment>
#include <QDebug>

int main() {
    QProcess process;
    QProcessEnvironment env;
    // 设置空的环境变量
    process.setProcessEnvironment(env);
    // 启动进程
    process.start("printenv");
    if (process.waitForFinished()) {
        QByteArray output = process.readAllStandardOutput();
        qDebug() << "Output:" << output;
    } else {
        qDebug() << "Process failed:" << process.errorString();
    }
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 七、插件系统

# 1. 插件框架

  • QPluginLoader:动态加载插件
  • QFactoryInterface:插件工厂接口
  • Q_GLOBAL_STATIC:全局静态对象

# 八、工具类与算法

# 1. 实用工具

  • QVariant:通用类型容器
  • QDebug:调试输出
  • QRandomGenerator:随机数生成
  • QCommandLineParser:命令行参数解析

# 2. 算法与函数式编程

  • QtAlgorithms:基本算法(已弃用,推荐 STL)
  • QtConcurrent:并行计算框架
  • QScopeGuard:作用域守卫(Qt 6)

# 九、国际化与本地化

# 1. 多语言支持

  • QTranslator:翻译加载器
  • QLocale:本地化信息(日期、货币等格式)
  • QCollator:字符串排序规则

# 十、内存管理

# 1. 智能指针

  • QSharedPointer:共享指针
  • QWeakPointer:弱引用指针
  • QScopedPointer:作用域指针
  • QPointer:QObject 感知指针

# 2. 对象生命周期

  • 父子对象树自动管理
  • QObject::deleteLater() 延迟删除

# 十二、系统集成

# 1. 平台抽象

  • QOperatingSystemVersion:操作系统版本检测
  • QSysInfo:系统信息
  • QStorageInfo:存储设备信息

# 2. 进程管理

  • QProcess:启动和控制外部进程
  • QProcessEnvironment:进程环境变量

# 十三、设计模式实现

# 1. 常用模式

  • 信号槽:观察者模式实现
  • QSingleton:单例模式模板
  • QStateMachine:状态机框架

# 十四、性能分析工具

# 1. 性能工具

  • QElapsedTimer:代码计时
  • QLoggingCategory:分类日志
  • QTest:单元测试框架(部分功能在 Qt Test 模块)

Qt 的插件框架(Plugin Framework)允许开发者将功能模块化,并通过动态加载插件的方式扩展应用程序的功能。插件框架的核心是 QPluginLoader 类,它用于加载和卸载插件。以下是 Qt 插件框架的详细使用方法:


# 1. 插件框架的基本概念

  • 插件(Plugin):
    • 插件是一个动态库(如 .dll、.so 或 .dylib),包含实现特定接口的类。
    • 插件通过实现预定义的接口来提供功能。
  • 接口(Interface):
    • 接口是一个纯虚类,定义了插件必须实现的方法。
  • 插件加载器(QPluginLoader):
    • 用于加载插件并获取插件实例。

# 2. 创建插件

# (1)定义接口

首先,定义一个接口类。接口类必须继承 QObject 并使用 Q_DECLARE_INTERFACE 宏声明。

// MyPluginInterface.h
#ifndef MYPLUGININTERFACE_H
#define MYPLUGININTERFACE_H

#include <QObject>
#include <QtPlugin>

class MyPluginInterface
{
public:
    virtual ~MyPluginInterface() {}
    virtual void doSomething() = 0; // 纯虚函数,插件必须实现
};

Q_DECLARE_INTERFACE(MyPluginInterface, "com.example.MyPluginInterface/1.0")

#endif // MYPLUGININTERFACE_H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# (2)实现插件

创建一个插件类,实现接口,并使用 Q_PLUGIN_METADATA 宏声明插件。

// MyPlugin.h
#ifndef MYPLUGIN_H
#define MYPLUGIN_H

#include "MyPluginInterface.h"
#include <QObject>

class MyPlugin : public QObject, public MyPluginInterface
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "com.example.MyPluginInterface/1.0")
    Q_INTERFACES(MyPluginInterface)

public:
    void doSomething() override {
        qDebug() << "MyPlugin is doing something!";
    }
};

#endif // MYPLUGIN_H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# (3)编译插件

将插件编译为动态库。在 .pro 文件中添加以下内容:

TEMPLATE = lib
CONFIG += plugin
SOURCES += MyPlugin.cpp
HEADERS += MyPlugin.h MyPluginInterface.h
1
2
3
4

编译后会生成一个动态库文件(如 libMyPlugin.so、MyPlugin.dll 等)。


# 3. 加载插件

# (1)使用 QPluginLoader 加载插件

在应用程序中,使用 QPluginLoader 加载插件并调用其功能。

#include <QCoreApplication>
#include <QPluginLoader>
#include <QDebug>
#include "MyPluginInterface.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 加载插件
    QPluginLoader pluginLoader("path/to/libMyPlugin.so"); // 替换为插件的路径
    QObject *pluginInstance = pluginLoader.instance();

    if (pluginInstance) {
        // 将插件实例转换为接口类型
        MyPluginInterface *plugin = qobject_cast<MyPluginInterface*>(pluginInstance);
        if (plugin) {
            plugin->doSomething(); // 调用插件功能
        } else {
            qDebug() << "Failed to cast plugin to MyPluginInterface.";
        }
    } else {
        qDebug() << "Failed to load plugin:" << pluginLoader.errorString();
    }

    return a.exec();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# (2)处理插件加载失败

如果插件加载失败,可以通过 QPluginLoader::errorString() 获取错误信息。


# 4. 插件的动态加载与卸载

QPluginLoader 支持动态加载和卸载插件。例如:

QPluginLoader pluginLoader("path/to/libMyPlugin.so");
if (pluginLoader.load()) {
    MyPluginInterface *plugin = qobject_cast<MyPluginInterface*>(pluginLoader.instance());
    if (plugin) {
        plugin->doSomething();
    }
    pluginLoader.unload(); // 卸载插件
}
1
2
3
4
5
6
7
8

# 5. 插件的元数据

使用 Q_PLUGIN_METADATA 宏可以为插件添加元数据。例如:

Q_PLUGIN_METADATA(IID "com.example.MyPluginInterface/1.0" FILE "metadata.json")
1

在 metadata.json 文件中定义元数据:

{
    "name": "MyPlugin",
    "version": "1.0",
    "author": "Example Inc."
}
1
2
3
4
5

可以通过 QPluginLoader::metaData() 获取插件的元数据。


# 6. 插件的搜索路径

Qt 会在以下路径中搜索插件:

  • 应用程序的 plugins 目录。
  • Qt 安装目录下的 plugins 目录。
  • 环境变量 QT_PLUGIN_PATH 指定的路径。

可以通过 QCoreApplication::addLibraryPath() 添加自定义插件路径。


# 7. 插件的多平台支持

插件的文件扩展名因平台而异:

  • Windows: .dll
  • Linux: .so
  • macOS: .dylib

可以使用 QLibraryInfo::location(QLibraryInfo::PluginsPath) 获取平台的插件路径。


# 8. 完整示例

# (1)插件接口

// MyPluginInterface.h
#ifndef MYPLUGININTERFACE_H
#define MYPLUGININTERFACE_H

#include <QObject>
#include <QtPlugin>

class MyPluginInterface
{
public:
    virtual ~MyPluginInterface() {}
    virtual void doSomething() = 0;
};

Q_DECLARE_INTERFACE(MyPluginInterface, "com.example.MyPluginInterface/1.0")

#endif // MYPLUGININTERFACE_H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# (2)插件实现

// MyPlugin.h
#ifndef MYPLUGIN_H
#define MYPLUGIN_H

#include "MyPluginInterface.h"
#include <QObject>

class MyPlugin : public QObject, public MyPluginInterface
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "com.example.MyPluginInterface/1.0")
    Q_INTERFACES(MyPluginInterface)

public:
    void doSomething() override {
        qDebug() << "MyPlugin is doing something!";
    }
};

#endif // MYPLUGIN_H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# (3)加载插件

#include <QCoreApplication>
#include <QPluginLoader>
#include <QDebug>
#include "MyPluginInterface.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QPluginLoader pluginLoader("path/to/libMyPlugin.so");
    QObject *pluginInstance = pluginLoader.instance();

    if (pluginInstance) {
        MyPluginInterface *plugin = qobject_cast<MyPluginInterface*>(pluginInstance);
        if (plugin) {
            plugin->doSomething();
        } else {
            qDebug() << "Failed to cast plugin to MyPluginInterface.";
        }
    } else {
        qDebug() << "Failed to load plugin:" << pluginLoader.errorString();
    }

    return a.exec();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 总结

Qt 的插件框架通过 QPluginLoader 和接口机制,实现了功能的模块化和动态扩展。通过定义接口、实现插件、加载插件,可以轻松扩展应用程序的功能。如果还有其他问题,请随时告诉我!

Qt 提供了许多实用工具类,可以简化开发过程。以下是 QVariant、QDebug、QRandomGenerator 和 QCommandLineParser 的详细使用方法:


# 1. QVariant:通用类型容器

QVariant 是 Qt 中的通用类型容器,可以存储各种类型的数据(如 int、QString、QList 等),并支持类型转换。

# (1)基本用法

#include <QVariant>
#include <QDebug>

int main()
{
    QVariant v1 = 42; // 存储整数
    QVariant v2 = "Hello, Qt!"; // 存储字符串
    QVariant v3 = 3.14; // 存储浮点数

    qDebug() << "v1:" << v1.toInt(); // 转换为整数
    qDebug() << "v2:" << v2.toString(); // 转换为字符串
    qDebug() << "v3:" << v3.toDouble(); // 转换为浮点数

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# (2)存储复杂类型

#include <QVariant>
#include <QStringList>
#include <QDebug>

int main()
{
    QStringList list = {"Apple", "Banana", "Cherry"};
    QVariant v = QVariant::fromValue(list); // 存储 QStringList

    QStringList retrievedList = v.value<QStringList>(); // 获取 QStringList
    qDebug() << "List:" << retrievedList;

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 2. QDebug:调试输出

QDebug 是 Qt 的调试输出工具,用于在控制台打印调试信息。

# (1)基本用法

#include <QDebug>

int main()
{
    int value = 42;
    QString text = "Hello, Qt!";

    qDebug() << "Value:" << value; // 输出变量
    qDebug() << "Text:" << text; // 输出字符串
    qDebug("This is a debug message: %d", value); // 格式化输出

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# (2)禁用调试输出

在发布版本中,可以通过定义 QT_NO_DEBUG_OUTPUT 宏禁用 qDebug 输出。

#define QT_NO_DEBUG_OUTPUT
#include <QDebug>

int main()
{
    qDebug() << "This will not be printed in release mode.";
    return 0;
}
1
2
3
4
5
6
7
8

# 3. QRandomGenerator:随机数生成

QRandomGenerator 是 Qt 提供的随机数生成器,用于生成高质量的随机数。

# (1)基本用法

#include <QRandomGenerator>
#include <QDebug>

int main()
{
    // 生成随机整数
    int randomInt = QRandomGenerator::global()->bounded(100); // 0 到 99
    qDebug() << "Random integer:" << randomInt;

    // 生成随机浮点数
    double randomDouble = QRandomGenerator::global()->generateDouble(); // 0.0 到 1.0
    qDebug() << "Random double:" << randomDouble;

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# (2)生成随机字符串

#include <QRandomGenerator>
#include <QString>
#include <QDebug>

QString generateRandomString(int length)
{
    const QString possibleCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    QString randomString;
    for (int i = 0; i < length; ++i) {
        int index = QRandomGenerator::global()->bounded(possibleCharacters.length());
        QChar nextChar = possibleCharacters.at(index);
        randomString.append(nextChar);
    }
    return randomString;
}

int main()
{
    QString randomStr = generateRandomString(10);
    qDebug() << "Random string:" << randomStr;

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 4. QCommandLineParser:命令行参数解析

QCommandLineParser 用于解析命令行参数,支持选项、参数和帮助信息。

# (1)基本用法

#include <QCoreApplication>
#include <QCommandLineParser>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName("MyApp");
    QCoreApplication::setApplicationVersion("1.0");

    QCommandLineParser parser;
    parser.setApplicationDescription("A simple command-line tool.");
    parser.addHelpOption();
    parser.addVersionOption();

    // 添加选项
    QCommandLineOption verboseOption("v", "Enable verbose mode.");
    parser.addOption(verboseOption);

    // 添加位置参数
    parser.addPositionalArgument("file", "The file to process.");

    // 解析命令行参数
    parser.process(app);

    // 检查选项
    if (parser.isSet(verboseOption)) {
        qDebug() << "Verbose mode enabled.";
    }

    // 获取位置参数
    QStringList positionalArgs = parser.positionalArguments();
    if (!positionalArgs.isEmpty()) {
        qDebug() << "File to process:" << positionalArgs.first();
    } else {
        qDebug() << "No file specified.";
    }

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

# (2)运行示例

假设程序名为 MyApp,运行以下命令:

./MyApp -v input.txt
1

输出:

Verbose mode enabled.
File to process: input.txt
1
2

# 总结

  • QVariant:用于存储和转换多种类型的数据。
  • QDebug:用于调试输出,支持格式化字符串。
  • QRandomGenerator:生成高质量的随机数。
  • QCommandLineParser:解析命令行参数,支持选项和位置参数。

这些工具类可以显著提高开发效率。如果还有其他问题,请随时告诉我!

Qt 提供了一些与算法和函数式编程相关的工具,包括 QtAlgorithms、QtConcurrent 和 QScopeGuard。以下是它们的详细使用方法:


# 1. QtAlgorithms:基本算法

QtAlgorithms 是 Qt 提供的一组基本算法(如排序、查找等),但自 Qt 5.15 起已被弃用,推荐使用 C++ 标准库(STL)中的算法。

# (1)弃用说明

QtAlgorithms 中的函数(如 qSort、qFind 等)已被弃用,建议使用 STL 中的 std::sort、std::find 等替代。

# (2)示例:使用 STL 替代 QtAlgorithms

#include <QList>
#include <algorithm>
#include <QDebug>

int main()
{
    QList<int> list = {3, 1, 4, 1, 5, 9, 2, 6};

    // 使用 std::sort 排序
    std::sort(list.begin(), list.end());

    // 使用 std::find 查找
    auto it = std::find(list.begin(), list.end(), 5);
    if (it != list.end()) {
        qDebug() << "Found value 5 at position:" << (it - list.begin());
    }

    qDebug() << "Sorted list:" << list;

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 2. QtConcurrent:并行计算框架

QtConcurrent 是 Qt 提供的并行计算框架,用于简化多线程编程。它支持并行执行函数、过滤和映射容器等操作。

# (1)基本用法

#include <QtConcurrent/QtConcurrent>
#include <QList>
#include <QDebug>

int square(int x)
{
    return x * x;
}

int main()
{
    QList<int> list = {1, 2, 3, 4, 5};

    // 并行计算每个元素的平方
    QFuture<int> future = QtConcurrent::mapped(list, square);

    // 等待计算完成并获取结果
    future.waitForFinished();
    QList<int> result = future.results();

    qDebug() << "Squared list:" << result;

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# (2)并行过滤

#include <QtConcurrent/QtConcurrent>
#include <QList>
#include <QDebug>

bool isEven(int x)
{
    return x % 2 == 0;
}

int main()
{
    QList<int> list = {1, 2, 3, 4, 5, 6};

    // 并行过滤偶数
    QFuture<int> future = QtConcurrent::filtered(list, isEven);

    // 等待过滤完成并获取结果
    future.waitForFinished();
    QList<int> result = future.results();

    qDebug() << "Even numbers:" << result;

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# (3)并行映射-归约

#include <QtConcurrent/QtConcurrent>
#include <QList>
#include <QDebug>

int sum(int x, int y)
{
    return x + y;
}

int main()
{
    QList<int> list = {1, 2, 3, 4, 5};

    // 并行计算列表元素的和
    QFuture<int> future = QtConcurrent::mappedReduced(list, square, sum);

    // 等待计算完成并获取结果
    future.waitForFinished();
    int result = future.result();

    qDebug() << "Sum of squares:" << result;

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 3. QScopeGuard:作用域守卫(Qt 6)

QScopeGuard 是 Qt 6 引入的工具,用于在作用域结束时自动执行清理操作(如释放资源、恢复状态等)。

# (1)基本用法

#include <QScopeGuard>
#include <QDebug>

void cleanup()
{
    qDebug() << "Cleanup function called!";
}

int main()
{
    // 创建作用域守卫
    auto guard = qScopeGuard([]() {
        qDebug() << "Lambda cleanup called!";
    });

    // 手动调用 cleanup 函数
    auto guard2 = qScopeGuard(cleanup);

    qDebug() << "Inside main function.";

    // 作用域结束时,guard 和 guard2 会自动调用其清理函数
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# (2)禁用作用域守卫

可以通过 QScopeGuard::dismiss() 禁用作用域守卫。

#include <QScopeGuard>
#include <QDebug>

int main()
{
    auto guard = qScopeGuard([]() {
        qDebug() << "This will not be called.";
    });

    guard.dismiss(); // 禁用作用域守卫

    qDebug() << "Inside main function.";

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 总结

  • QtAlgorithms:已弃用,推荐使用 STL 中的算法。
  • QtConcurrent:用于简化并行计算,支持映射、过滤和归约操作。
  • QScopeGuard:用于在作用域结束时自动执行清理操作。

这些工具可以显著提高代码的简洁性和可维护性。如果还有其他问题,请随时告诉我!

上次更新: 2026/06/10, 11:13:41
容器类和算法
README

← 容器类和算法 README→

最近更新
01
信号崩溃快速排查
06-15
02
CoreDump破案
06-15
03
perf火焰图实战
06-15
更多文章>
Theme by Vdoing | Copyright © 2019-2026 杨充 | MIT License | 桂ICP备2024034950号 | 桂公网安备45142202000030
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式