问题
Let's say SomeClass
has members Object1
and Object2
and there is a connection between Object1
and Object2
like:
connect(Object1, signal1, Object2, slot1)
After some refactoring Object3
was added to SomeClass
and Object2
was moved to be a member of Object3
, but still exist the need for the connection between Object1
and Object2
.
The communication between Object1
and Object2
will have to go through Object3
now. This means Object3
needs to be modified, adding a pair of signal/slot just to implement that communication between Object1
and Object2
.
This means both Object3
's .h and .cpp will be modified, adding many lines of code to do a thing previously done in just one line.
My lazy side is telling that there is something strange in this story. Is there some way to make that connection more straight forward?
回答1:
You're encapsulating Object2
within Object3
. From the point of view of the user of Object3
, nothing is changing: there's still only one line of code to set up the connection. Object3
needs an extra slot that forwards to the Object2
instance it now encapsulates. That's one extra line here. And that's it.
struct Object1 : QObject {
Q_SIGNAL void signal1();
Q_OBJECT
};
struct Object2 : QObject {
Q_SLOT void slot1() {}
Q_OBJECT
};
class Object3 : QObject {
Q_OBJECT
Object2 m_object2;
public:
// one line to expose object2's slot
Q_SLOT void slot1() { m_object2.slot1(); }
};
class SomeClass {
Object1 m_object1;
Object3 m_object2;
public:
SomeClass() {
// still one line
connect(&m_object1, &Object1::signal1, &m_object3, &Object3::slot1);
}
};
来源:https://stackoverflow.com/questions/38251956/qt-forwarding-signal-slot-connections