变更内容Qt Concurrent
Qt 6 的变更,是出于让该框架更高效、更易于使用的有意识努力。
我们力求在每个版本中保持所有公开 API 的二进制兼容性和源代码兼容性。但在努力使 Qt 成为更优秀的框架的过程中,某些变更在所难免。
在本主题中,我们将总结Qt Concurrent 中的这些变更,并提供相应的处理指南。
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 的其他方法行为未发生变化,也不会导致源代码兼容性问题。
© 2026 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.