如何通过QtConcurrent调用带有参数的函数

use*_*975 1 c++ qt multithreading

在我的应用程序中,有一个保存过程阻止了我的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
    }    
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的

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
    }    
}
Run Code Online (Sandbox Code Playgroud)

此外,在标头中,我包括以下内容:

#include <QtConcurrent/QtConcurrentRun>
Run Code Online (Sandbox Code Playgroud)

错误消息是

C:\App\appname\traymenu.cpp:584: Error: no matching function for call 
to 'run(<unresolved overloaded function type>, QString&)'
             QFuture<void> future = QtConcurrent::run(save, outputFilename);
                                                                          ^
Run Code Online (Sandbox Code Playgroud)

我也尝试过这个:

QFuture<void> future = QtConcurrent::run(this, this->save(outputFilename));
Run Code Online (Sandbox Code Playgroud)

那里的错误是

C:\App\appname\traymenu.cpp:584: Error: invalid use of void expression
                 QFuture<void> future = QtConcurrent::run(this, this->save(outputFilename));
                                                                                      ^
Run Code Online (Sandbox Code Playgroud)

我的标题如下:

class Traymenu : public QSystemTrayIcon
{
    Q_OBJECT
public:
    Traymenu(QApplication *);
    ~Traymenu();

    void save();        
    void saveNotes(QString);     
    //[...]     
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

lpa*_*app 6

从官方文档中:

使用成员函数

QtConcurrent :: run()也接受指向成员函数的指针。第一个参数必须是const引用或指向类实例的指针。调用const成员函数时,通过const引用传递很有用。通过指针传递对于调用修改实例的非常量成员函数很有用。

这意味着您将编写此代码以使其正常工作:

QtConcurrent::run(this, &Traymenu::saveNotes, outputFileName);
Run Code Online (Sandbox Code Playgroud)