connectSlotsByName can not be trusted?
-
Hi,
recently, I found a very interesting thing.
I have a project use a lot of button, so I dont want to name them one by one. then I used connectSlotsByName to connect buttons with signals.one day I show a Dialog with customized widget which contains a tool button named toolButton from the main window, and in my main window there is also a toolButton. to use connectSlotsByName , I create a slot function named on_toolButton_clicked for each widget. when I clicked the tooButton from the main widget, there is no slot being called, but when I clicked the toolButton from the dialog widget, all the two slot were called.
I am using Qt5.12.10 with vs2017 on windows 10, is this normal phenomenon? if I want to avoid this problem, rename the slot function is the only way?
thank you very much.
-
Without seeing your code it is not possible to say with certainty is going wrong here. However,
connectSlotsByName()
searches recursively from the object you provide the function, which means it may find more than one function (from different classes) called on_toolButton_clicked and connect only the last. This convenience function is usually on called in a constructor at a time when there are no non-trivial QObject child objects that that lead to this ambuguity. Your main window connections should be connected at construction; before the child dialog is constructed and callsconnectSlotsByName()
on itself. -
@Mozzie said in connectSlotsByName can not be trusted?:
all the two slot were called.
This has been noted before for
connectSlotsByName()
. As @ChrisW67 notes: if you have two identically named widgets at different levels in the hierarchy you will end up with both connected, because of the recursive search. The simple long-and-short is: do not useconnectSlotsByName()
, do allconnect()
s explicitly yourself. -
Hi
Nope, it can't be trusted. :)
You can obtain the same auto connect using FindChildren and lambdas.