Can Qt signals be public or private?

Viewed 39065

Can Qt signals be public or private? Can I create internal signals, which are seen only inside the class?

Update: I have a class with some internal signals. How can I make those signals invisible for other classes (encapsulation & information hiding)?

8 Answers

No. Signals cannot be public or private. Qt signals are protected class methods.

"signals" keyword is defined in qobjectdefs.h (line 69 as for Qt 4.6.1):

#   define signals protected

UPDATE: signals are only protected upto and including all minor versions of Qt 4. From Qt 5.0 onwards they are public. See https://stackoverflow.com/a/19130831.

Slots are simple methods which can be public, protected, or private.

As Andrei pointed it out, signal are only a redefinition of protected, meaning they can only be emitted by the class in which they are defined.

If you want to make a class emit a signal from anoter one, you have to add it a public method (or slot) like this one:

void emitTheSignal(...) {
  emit theSignal(...);
}

Qt signals are public in the sense that any object can connect to any signal.

All the existing answers are incorrect.

A signal can be made private by adding a QPrivateSignal type to its definition as the last argument:

signals:
  
  void mySignal(QPrivateSignal);

QPrivateSignal is a private struct created in each QObject subclass by the Q_OBJECT macro, so you can only create QPrivateSignal objects in the current class.

Technically, the signal still has public visibility, but it can only be emitted by the class that created it.

You can use the PIMPL pattern for that. Your private signals exists in the private implementation only.

Nowadays you can use Q_SIGNAL macro and normal C++ access specifier:

protected:
  Q_SIGNAL void myProtectedSignal();

private:
  Q_SIGNAL void myPrivateSignal();
Related