Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

connect() of signal passing parameters not wanted by slot



  • Stylistic opinion/what you do wanted, please.

    When I have a signal which passes some parameters and I want to connect() it to a slot of mine which is not interested in/does not use the parameters, for clarity I end up writing a stub lambda just to received but ignore the parameters, e.g.

    connect(spinBox, &QSpinBox::valueChanged,
            this, [this](int /*i*/) { existingMethodWithNoParameters(); });
    // or (something like)
    connect(model, &QAbstractItemModel::dataChanged,
            this, [this](const QModelIndex &/*topLeft*/,
                         const QModelIndex &/*bottomRight*/,
                         const QVector<int> &/*roles*/ = QVector<int>()) { existingMethodWithNoParameters(); });
    

    Is this what you would do? I am getting a bit fed up with quite a lot of these, I would prefer to write these as direct slot calls:

    connect(spinBox, &QSpinBox::valueChanged,
            this, &ThisClass::existingMethodWithNoParameters);
    // or
    connect(model, &QAbstractItemModel::dataChanged,
            this, &ThisClass::existingMethodWithNoParameters);
    

    connect() seems to be quite happy attaching a slot without these matching parameters, as shown, no compiler complaint. (And I equally don't fancy writing a fully matching slot just to call the desired non-parameter method.) Would you be happy abbreviating like this? Or do you think that is "bad form" and I should spell out the passed-in parameters and write a lambda each time?


  • Lifetime Qt Champion

    @JonB A slot does not have to have parameters. You can for example connect a slot without parameters to a signal with parameters. What is not allowed is the other way around. So, in my opinion it is perfectly fine to omit the parameters in the slot.


  • Lifetime Qt Champion

    @JonB A slot does not have to have parameters. You can for example connect a slot without parameters to a signal with parameters. What is not allowed is the other way around. So, in my opinion it is perfectly fine to omit the parameters in the slot.



  • @jsulm
    Good! In that case I can go tidy my code. (Unless a purist disagrees before today is out!) I do prefer one-liners/less characters to type, easier to read and it will improve my compilation speed (and maybe runtime) :)


Log in to reply