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

标签 c++ multithreading qt

<分区>

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

我也试过这个:

QFuture<void> future = QtConcurrent::run(this, this->save(outputFilename));

这里有错误

C:\App\appname\traymenu.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);     
    //[...]     

我做错了什么?

最佳答案

来自official documentation :

Using Member Functions

QtConcurrent::run() also accepts pointers to member functions. The first argument must be either a const reference or a pointer to an instance of the class. Passing by const reference is useful when calling const member functions; passing by pointer is useful for calling non-const member functions that modify the instance.

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

QtConcurrent::run(this, &Traymenu::saveNotes, outputFileName);

关于c++ - 如何通过 QtConcurrent 调用带参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23702930/

相关文章:

android设置定时器按钮的可见性

c++ - QTreeWidget 子类,停止放置指示器显示给定的不需要的 dropIndicatorPosition

c++ - clock() 只返回 0

c++ - 如何使用存在于另一个文件中的 WndProc 中的函数

python - pygame - 如何在没有 time.sleep() 的情况下缓慢更新 HP 条

c++ - 在生成的线程中启动进程

Qt/C++ : How to get remote PC (communication peer) MAC address?

c++ - 如何使用折叠表达式创建 N 个浮点值的数组?

C++ - 私有(private)数据成员

c - pthread rwlock : rdlock inside wrlock