如何通过QtConcurrent调用带参数的函数
How to call a function with arguments by QtConcurrent
在我的应用程序中有一个保存过程阻塞了我的UI。优化是不够的,所以我想用QtConcurrent
实现线程,但我不能让它工作,虽然语法看起来很容易。
这就是它现在的样子(原则):
Traymenu::Traymenu(QApplication *a){
//...
void save(){
//Get the savepath, choose if saving is necessary, and trigger saving
QString path = getSavePath();
saveNotes(path);
}
void saveNotes(QString savePath){
//save to the given path, takes quite a while, should be parallel
}
}
我已经试过了:
Traymenu::Traymenu(QApplication *a){
//...
void save(){
//Get the savepath, choose if saving is necessary, and trigger saving
QString path = getSavePath();
QFuture<void> result = QtConcurrent(saveNotes, path); //ERROR
}
void saveNotes(QString savePath){
//save to the given path
}
}
此外,在我的标题中,我包括了这个:
#include <QtConcurrent/QtConcurrentRun>
错误信息是
C:Appappnametraymenu.cpp:584: Error: no matching function for call
to 'run(<unresolved overloaded function type>, QString&)'
QFuture<void> future = QtConcurrent::run(save, outputFilename);
^
我也试过这个:
QFuture<void> future = QtConcurrent::run(this, this->save(outputFilename));
错误在
C:Appappnametraymenu.cpp:584: Error: invalid use of void expression
QFuture<void> future = QtConcurrent::run(this, this->save(outputFilename));
^
我的头看起来像:
class Traymenu : public QSystemTrayIcon
{
Q_OBJECT
public:
Traymenu(QApplication *);
~Traymenu();
void save();
void saveNotes(QString);
//[...]
我做错了什么?
来自官方文档:
使用成员函数
QtConcurrent::run()也接受成员函数的指针。第一个实参必须是const引用或指向类实例的指针。在调用const成员函数时,通过const引用传递是有用的;通过指针传递对于调用修改实例的非const成员函数很有用。
这意味着你要这样写才能使它工作:
QtConcurrent::run(this, &Traymenu::saveNotes, outputFileName);
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类