[Development] Proposal to change connectSlotsByName behavior
b.terrier at gmail.com
Fri Dec 4 00:05:19 CET 2015
This message follows an exchange I've had with Thiago on a bug report:
In the current state, QMetaObject::connectSlotsByName() tries to find,
for each slot named "on_<anObjectName>_<aSignalName>" in a given
a child object named <anObjectName>" and connect the signal to the
slot. Moreover the documentation says that the search is recursive so
descendant QObject is looked up (not only direct children).
My issue here is that the search is done by instantiation order
(depth-first search) which means that if 2 (or more) children have the
same name one has
to know which one is instantiated first to know which one will be
connected. And of course imposing on the developer to use unique names
a QObject hierarchy is not feasible in particular if he/she is using a
third-party library and might not know the object names used
This can lead to various hazardous situation, for instance, in a
perfectly working software, one can break the behavior of the main
window by simply adding
a widget in a grand-grand-child widget.
Or worse if the UI is made using Qt Designer, the behavior of the
application can be changed by simply reordering the widgets in the
layout as it will also
change their creation order.
An application could even break at runtime if a user enables a plugin
or set an HMI element visible.
In my opinion it also breaks encapsulation as the naming in a widget
can alter the signal/slot connections in another widget.
My proposal is to change the behavior of connectSlotsByName to do a
breadth-first search. In this case, if a direct child is a match it
will be used
for the connection regardless of possible matches deeper in the
hierarchy. Doing so would solve the situations stated above and
It seems that Thiago's opinion is that it can not be changed as this
behavior has been here since Qt 4 and it might break existing
On my side I think it's at least a buggy and error prone behavior or
even a flawed design and that it must be changed as soon as possible.
About the risk of breaking existing applications,
I think making the change is less risky for Qt users as in the current
state every Qt software can break with any change to an object name or
Also as Qt Designer does push the users to use the connectSlotsByName
mechanism, it is even possible to generate an example of this
without writing a single line of code (see attached zip in the bug report).
More information about the Development