我认为这里的主要问题是信号不是静态成员函数。因此,它们需要一个指向类实例的指针才能正确调用。所以你不能只传递&VMyView::Signal 之类的东西,因为函数没有相应的this 指针。 (这就是为什么大多数QObject::connect() 重载都需要发送方/接收方对象的实例。)
解决这个问题的一种方法是创建一个函数对象,它包含成员函数指针和指向调用它的对象的指针。这可以传递给QObject::connect() 函数就好了。
这是一个例子:
// objects.h
#include <QtCore>
class Receiver : public QObject
{
Q_OBJECT
public:
Receiver( QObject *parent = nullptr)
: QObject(parent)
{
}
~Receiver() { }
signals:
void sig(void);
};
class Sender : public QObject
{
Q_OBJECT
public:
Sender(std::function<void(void)> &bound_signal, QObject *parent = nullptr)
: QObject(parent)
{
// automatically emit `Sender::sig` on a timer, for testing.
timer = new QTimer(this);
timer->setInterval(1000);
QObject::connect(timer, &QTimer::timeout, this, &Sender::sig);
QObject::connect(this, &Sender::sig, bound_signal);
timer->start();
}
~Sender() { }
signals:
void sig(void);
private:
QTimer *timer;
};
然后是一个主函数:
// main.cc
#include <QtCore>
#include "objects.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
Receiver receiver; // object to receive the signal
// Bind the receiver's signal to the instance of the class
std::function<void(void)> signal = std::bind(&Receiver::sig, &receiver);
// Create a Sender, which will connect its own signal to the
// given bound signal
Sender sender(signal);
QObject::connect(&receiver, &Receiver::sig,
[]() -> void { qDebug() << "received"; });
return app.exec();
}
因此,在您的情况下,Receiver 及其信号将替换为 VMyView 和您想要链接的信号,Sender 将是您实现的自定义复选框类。然后在复选框类的构造函数中,将您想要的任何信号连接到给定的 bound 信号。您还可以传入绑定信号列表,例如std::list<std::function<void(void)>> &bound_signals。
不过,我不得不说,我不确定这会给你带来什么。您需要在某处编写连接逻辑,我不明白为什么它需要在复选框类的构造函数中。无论在哪里创建和使用复选框和 VMyView 类,这似乎都是放置连接代码的更好位置。它更明显,不那么复杂,并且有更好的关注点分离。复选框类不必知道或关心它连接到的信号/插槽。应用程序逻辑(即对象在哪里使用)应该定义对象如何相互交互。