private/public qt signals

前端 未结 7 2253
情话喂你
情话喂你 2020-12-10 00:36

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

相关标签:
7条回答
  • 2020-12-10 01:10

    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.

    0 讨论(0)
  • 2020-12-10 01:16

    A common way, e.g. seen in kdelibs, is this:

    Q_SIGNALS:
    #ifndef Q_MOC_RUN
        private: // don't tell moc, doxygen or kdevelop, but those signals are in fact private
    #endif
    
       void somePrivateSignal();
    

    This makes the signal private, i.e. it can only be emitted by the class itself but not by its subclasses. To not make the "private:" overrule Q_SIGNALS (moc wouldn't see somePrivateSignal as signal then), it's inside Q_MOC_RUN, which is only defined when moc runs.

    Edit: This approach doesn't work for the new-style connects introduced with Qt 5 (connect(a, &A::someSignal, b, &B::someSlot)), as they require the signal to be accessible.

    0 讨论(0)
  • 2020-12-10 01:18

    Signals was protected in Qt4, in Qt5 they are public. Int Qt5 you can make them private by adding QPrivateSignal as the last argument. More on this: http://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html

    0 讨论(0)
  • 2020-12-10 01:18

    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(...);
    }
    
    0 讨论(0)
  • 2020-12-10 01:18

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

    0 讨论(0)
  • 2020-12-10 01:21

    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.

    0 讨论(0)
提交回复
热议问题