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

How to call a function with arguments by QtConcurrent

本文关键字:参数 函数 调用 何通过 QtConcurrent      更新时间:2023-10-16

在我的应用程序中有一个保存过程阻塞了我的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);