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

Connect slot of "wrong" (but derived) class



  • Gurus' opinions wanted :)

    While messing about I deliberately tried this:

    class AWidget : public QWidget
    {
        void method()
        {
            connect(something, &Something::signal, this, &QPushButton::setEnabled);
        }
    }
    

    Note that it is class QWidget but the slot is QPushButton::setEnabled().

    This compiles (gcc, I think I am (default) C++11) without warning and works. Because, I guess, QPushButton does not have its own setEnabled() but inherits it directly from QWidget.

    At some future date, QPushButton::setEnabled() is given its own override. At which point (I presume) compilation will error and I'll have to change to &QWidget::setEnabled. Which is what I should have written in the first place.

    Should C++ compiler warn me about this in the first place, to avoid this? Discuss :)


  • Lifetime Qt Champion

    See it as an offsetOf() - it finds the offset of QPushButton::setEnabled and uses them - no more checks can be done here by the compiler.


  • Lifetime Qt Champion

    I don't see how a compiler could warn here. You have to pass a function pointer to an existing function what you're doing here.



  • @Christian-Ehrlicher

    connect(something, &Something::signal, this, &QPushButton::setEnabled);

    this is a QWidget. Writing &QPushButton::setEnabled, from my point of view at least, means I am looking for a method of a QPushButton. Which is not suitable for a QWidget!

    If I wrote &QPushButton::showMenu it would compile-error. If I could find some method of QWidget which QPushButton overrides, I believe that would error too. It only accepts &QPushButton::setEnabled because there is a &QWidget::setEnabled inherited unchanged by QPushButton.

    When this is a QWidget, I don't want to be allowed to specify a method via &QPushButton::anything. Only via &QWidget::something. Safe, right. Can't I have that?


  • Lifetime Qt Champion

    See it as an offsetOf() - it finds the offset of QPushButton::setEnabled and uses them - no more checks can be done here by the compiler.



  • @Christian-Ehrlicher
    Yep, thanks @Christian-Ehrlicher, at least I know where I am :)
    I'll mark yours as solution tomorrow, just in case anyone else finds this worthy of commenting in....


Log in to reply