c++ - 将 QObject 接口(interface)信号连接到 lambda 插槽

标签 c++ qt c++11 lambda

我正在尝试将 QObject 信号连接到 lambda 槽,但使用指向对象的接口(interface)指针而不是指向具体 QObject 类的指针。但是我得到了这个奇怪的错误:

 error: no matching function for call to ‘FileSystemModel::connect(model_filesystem::Directory*&, const char*, FileSystemModel::setDirectory(model_filesystem::Directory*)::<lambda()>)’
 });

这是我的一些代码片段:

// Interface declaration
namespace model_filesystem {

class Directory {
public:

    virtual ~Directory()
    virtual QString name() = 0;

Q_SIGNALS:
        void changed();
        void failure(QString msg);
    };
}

Q_DECLARE_INTERFACE(model_filesystem::Directory, "org.moonlightde.panel.model_filesystem.Directory/1.0")

//Implementation
class GVFSDirectory : public QObject,  public model_filesystem::Directory {
    Q_OBJECT
    Q_INTERFACES(model_filesystem::Directory)
public:
    GVFSDirectory(const QString &uri);
    GVFSDirectory(GFile * gfile);

    virtual ~GVFSDirectory();

    virtual QString name();
public Q_SLOTS:
    void update();

Q_SIGNALS:
    void changed();
    void failure(QString msg);

// Usage
Directory * directory = new GVFSDirectory("/");
connect(directory, SIGNAL(model_filesystem::Directory::changed()), [this] () {
    setupModel();
});

最佳答案

error: no matching function for call to ‘FileSystemModel::connect(model_filesystem::Directory ...

Directory 类不是QObject。如果要使用信号和/或,它需要子类QObject

来自 Qt5 - Signals & Slots :

All classes that inherit from QObject or one of its subclasses (e.g., QWidget) can contain signals and slots.

来自 Qt5 - Plug & Paint Example :

To make it possible to query at run-time whether a plugin implements a given interface, we must use the Q_DECLARE_INTERFACE() macro.

这似乎提供了在运行时查询插件是否实现了给定接口(interface)的机制,所以我不明白为什么应该对 Directory 有任何期望类应该像 QObject 一样工作,而无需对其进行子类化。

换句话说,不用继承 QObject 就可以使用它,但这不会授予 Directory 使用信号和/或插槽

SIGNAL(model_filesystem::Directory::update())

即使 Directory 是一个 QObject 也没有 update 信号,只有 changedfailure

关于c++ - 将 QObject 接口(interface)信号连接到 lambda 插槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838080/

相关文章:

qt - 如何在 Qt 中模拟消息总线?

c++ - QList::iterator 只返回 (error)0

c++ - std::bind 类内部,事件系统的一般概念

c++ - 如何使用 SFINAE 为枚举类中的缺失值制作 polyfill?

c++11 随机 double 使用 uniform_real_distribution

c++ - void指针的内容怎么写?

c++ - 循环条件中的空 vector<Point> size() 会导致奇怪的行为

c++ - POSIX 队列配置

c++ - 如何从 QMetaObject::invokeMethod 获取返回值

c++ - 在 C++ 中计算 log-sum-exp 函数