Qt Concurrent

Qt 6 是我们努力使框架更高效、更易用的结果。

我们尝试在每个版本中保持所有公共 API 的二进制和源代码兼容性。但为了使 Qt 成为一个更好的框架,有些改动是不可避免的。

在本主题中,我们总结了Qt Concurrent 中的这些变化,并提供了处理这些变化的指导。

QtConcurrent::run()

QtConcurrent::run() 已改进为可变参数数,因此其签名被修改为: QtConcurrent::run() 已改进为可变参数数:

// run
template <typename T>
QFuture<T> run(Function &&f, Args &&...args)

// run with a QThreadPool argument
template <typename T>
QFuture<T> run(QThreadPool *pool, Function &&f, Args &&...args)

作为副作用,如果f 是指向成员函数的指针,那么args 的第一个参数应该是定义该成员函数的对象(或引用,或指向它的指针)。因此,与其写

QImage image = ...;
QFuture<void> future = QtConcurrent::run(&image, &QImage::invertPixels, QImage::InvertRgba);

你必须写

QFuture<void> future = QtConcurrent::run(&QImage::invertPixels, &image, QImage::InvertRgba);

另一个副作用是,QtConcurrent::run() 将不再适用于重载函数。例如,下面的代码将无法编译:

void foo(int arg);
void foo(int arg1, int arg2);
...
QFuture<void> future = QtConcurrent::run(foo, 42);

最简单的解决方法是通过 lambda 调用重载函数:

QFuture<void> future = QtConcurrent::run([] { foo(42); });

或者,你也可以使用static_cast 告诉编译器选择哪个重载函数:

QFuture<void> future = QtConcurrent::run(static_cast<void(*)(int)>(foo), 42);

qOverload

QFuture<void> future = QtConcurrent::run(qOverload<int>(foo), 42);

QtConcurrent 的其他方法不会改变行为,也不会引入源代码兼容性问题。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.