Search code examples
c++qtqt5signals-slots

Does it worth keeping using the 'slots' mark in Qt 5?


I understand very well the benefits and drawbacks of using the new syntax for connecting slots in Qt 5. Just to mention some:

Pros:

  • Compile time checks (the slots exists, compatible arguments...)
  • Possibility to use lambdas (useful for very short and specific slots)
  • Protecting private/protected slots from being called from outside the class (ref)

Contras:

  • More complicate syntax in certain cases (specially overloads)
  • No support for slots with arguments with a default value

I also know that there are some (very few) cases where it is not possible (yet) to use the new syntax (QFileDialog::open).

Now, for the old syntax we had to mark those methods as slots in their definition, to mark the class with the Q_OBJECT macro, to moc it, and to inherit from QObject. As mentioned above, the new syntax doesn't require the methods to me marked as slots.

Is there any advantage of keeping the slots specifier when using (and only using) the new syntax? If the slots are the only QMetaObject's featured used by a class, we could then avoid the necessity to mark the class as Q_OBJECT, or even to inherit from QObject itself.


Solution

  • If the slots are the only QMetaObject's featured used by a class, we could then avoid the necessity to mark the class as Q_OBJECT, or even to inherit from QObject itself.

    You still need to inherit from QObject itself because you need an object to invoke the function on. That object must inherit from QObject so that Qt can detect which thread it is on (slot invocation may need to queued on a different thread) and to handle automatic disconnection when the receiver is destroyed.

    However, you can work around this without too much trouble by passing the signalling QObject as the receiving object and using a lambda:

    connect(qObjectInstance, &QObjectClass::signal, qObjectInstance, [&](){
        notAQObject->slot();
    });
    

    But you will have to manage the disconnection yourself if notAQObject could be destroyed before the signalling QObject.

    As far as the slots macro: if you are using strictly C++ and are not looking up slots through QMetaObject, slots doesn't do anything for you. slots or something similar (Q_INVOKABLE) is often necessary if you are inter-operating with something that uses the Qt MetaObject system more (such as QML).