While the answers by vahancho and TheDarkKnight are valid: slots
is not required for connections, but it makes the intent clearer and allows introspection. I think I should list some use cases where you do need slots
.
First please note that you can use slots
, Q_SLOTS
, Q_SLOT
or Q_INVOKABLE
to make a function known to the meta object (introspection) system. Q_INVOKABLE
has the advantage that it can be used on constructors.
And here are the use cases in no particular order:
- Make your code works with Qt 4. Even if Qt 4 is not maintained I think some big company are still using it and it is fairly easy to make a library works with Qt 5 and Qt 4.
- Make the function available in QML (and Qt Quick)
- Make the function available in javascript (Qt Script, Qt WebEngine, etc.)
- Make the function callable with
QMetaObject::invokeMethod()
. An overload that accepts functors will be available in Qt 5.10.
- Make use of
QMetaObject::connectSlotsByName()
. Note that this function should not be used as it can be affected by object name collisions, but it is still the way the Qt widget designer connects the slots it creates.
- Make your class instantiatable with
QMetaObject::newInstance()
.
- And every other use case that requires run-time introspection
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…