Confusions between GoToSlot GUI vs Connect Manually



  • Hi there,

    I'm new to QT and hope to learn a lot from you guys.

    My confusion is, we can connect a button's signal with a slot using Connect function in script, which we can see as we wrote it and change the function name and it still works.

    but when we simply select Go To Slot from GUI, select the signal and QT generates an event handler for that which works. but i dont see its "connect" code happening anywhere. which means if i change the generated event handler name it no longers work.

    please advise
    which feature i should prefer?

    Thanks


  • Moderators

    The code for the connection is created as part of the ui generation i.e. it is done when you call ui->setupUi(this) in your widget.
    If you look into the generated header file (the ui_YourClassName.h file) there's a call to QMetaObject::connectSlotsByName(). This is the method that does it.

    Personally I don't like it and don't use it at all. My 3 reasons for that are:

    • It's "magic" i.e. if you don't know about it there's no easy way to discover it. It's easy to forget about it and accidentally break by renaming something.
    • If you change the object name you need to change the slot name and vice versa. This creates dependency between two objects. It's artificial and unnecessary. The idea behind signal/slots is exactly the opposite - it allows to connect objects without such hard dependencies.
    • It enforces the usage of the snake_case syntax for the slot and the on_* naming convention that I don't use and would look weird in my code base. I'm naming my slots for what they do, not what they react to i.e. doSomething() instead of onSomethingHappened(), because that self-comments the method about what it is doing.

  • Qt Champions 2017

    Hi
    The most solid approach is using the new connect syntax
    https://wiki.qt.io/New_Signal_Slot_Syntax

    connect(
        sender, &Sender::valueChanged,
        receiver, &Receiver::updateValue
    );
    

    As it will fail compile time if anything wrong and not at runtime as with both
    QMetaObject::connectSlotsByName() and SLOT()/SIGNAL() syntax

    I like the connectSlotsByName() for prototyping but as Chris pointed out its
    a bit too magical and breaks so easy so using it in production code is asking for troubles.



  • Thank you very much guys for the support, no doubt QT has one of the best communities.
    @mrjj you are a champion, thank you for this tip.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.