c_cpp 通用QRunnable实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 通用QRunnable实现相关的知识,希望对你有一定的参考价值。

// Java sucks, and importing design patterns from Java sucks even more.
//
// This template avoids writing one QRunnable derived class per use case
// by wrapping any C++ callable.

template<typename Function>
struct Task : public QRunnable, Function
{
    template<typename... Args>
    Task(Args&&... args) :
        Function{std::forward<Args>(args)...}
    {}
    
    void run() override final // Well, this is the only thing copyed from Java that makes sense
    {
        Function::function();
    }
};

template<typename Function>
Task<typename std::decay<Function>::type>* makeTask(Function&& function)
{
    return new Task<typename std::decay<Function>::type>{std::forward<Function>(function)};
}

// Posting an arbitrary task to a Qt thread pool never was this easy

QThreadPool::globalInstance()->start(makeTask([&std::cout]
{
    std::cout << "Fuck you\n";
});

QThreadPool::globalInstance()->start(makeTask([this]
{
    myMethod();
});

QThreadPool::globalInstance()->start(makeTask([businessOp]
{
    businessOp.run();
});

以上是关于c_cpp 通用QRunnable实现的主要内容,如果未能解决你的问题,请参考以下文章

如何杀死 PyQt5 中的 QRunnable?

重用 QRunnable

多继承自 QObject 和 QRunnable 错误

C++/Qt - QThread 与 QRunnable

完成后将 QRunnable 连接到函数/方法

停止 QRunnable 导致主窗口无法关闭