I have a QObject A, this is connected to another QObject B. Now I want A to connect to C, a third QObject and to completely disconnect from B.
Easy peasy! Trouble is I have a lot of of A's each with their own set of signals and slots (B's/C's are more generic). So far I have been manually making a connect and a disconnect method for each different class type. The methods are basically copies of each other exchanging the connect
for disconnect
call, going against the don't repeat yourself).
So my question is: Is the following function possible?
void deleteAllConnections(QObject* someObject) {
// TODO disconnect all connections owned by someObject
// For bonus points: Is there a way of accessing the QMetaObject connected to?
}
I've poked around in the QMetaObject, QObject and the Signals and Slots documentation with no luck (though that is often not a guarantee...).
There are at least 2 ways. First, disconnect everything.
Second. Every
connect()
returnsQMetaObject::Connection
which can be copied or moved, so you can save some connections in the list and after some time, just iterate through the list and calldisconnect()
for every object. Example with one connection:Bonus: no, Qt doesn't support such deep introspection, you can't get list of all connected slots or something another, but in most cases, you don't need this at all. One useful info, that Qt gives you is
sender()
, pointer to object that sent signal.Edit
As doc said:
So in the next example both windows will be shown:
But uncomment
a->disconnect();
and onlyA
windows will be shown. It means thatQObject::connect(b,SIGNAL(objectNameChanged(QString)),a,SLOT(show()));
was not disconnected as stated in the doc. If you want to solve this puzzle you can doa->disconnect(b);b->disconnect(a);
, but it is of course very bad approach. So you can use second suggestion from my answer: