I understand how to use it, but the syntax of it bothers me. What is "private slots:" doing?
I have never seen something between the private keyword and the : in a class definition before. Is there some fancy C++ magic going on here?
And example here:
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
...
slots
is defined as #define slots
. When compiling using Qt MOC it generates code for the C++ compiler.
Slots are a Qt-specific extension of C++. It only compiles after sending the code through Qt's preprocessor, the Meta-Object Compiler (moc). See http://doc.qt.io/qt-5/moc.html for documentation.
Edit: As Frank points out, moc is only required for linking. The extra keywords are #defined away with the standard preprocessor.
The keywords such as public
, private
are ignored for Qt slots. All slots are actually public and can be connected
this
in the way we are familiar with.
Declaring slots as private means that you won't be able to reference them from context in which they are private, like any other method. Consequently you won't be able to pass private slots address to connect
.
If you declare signal as private you are saying that only this class can manage it but function member pointers do not have access restrictions:
class A{
private:
void e(){
}
public:
auto getPointer(){
return &A::e;
}
};
int main()
{
A a;
auto P=a.getPointer();
(a.*P)();
}
Other than that, what other answers mention is valid too:
- you still can connect private signals and slots from outside with tricks
- signals
and slots
are empty macros and do not break language standard
slots
is a macro helpful. I cannot connect private slot-function-pointers to connect
without tricks, can I?
Success story sharing
slots
keyword necessary? I've tried compiling/linking a few tiny Qt programs that call slots without theslots
keyword and they have built just fine. My experiments show that:signals:
is definitely necessary,slots
might be unnecessary, andemit
seems to be unnecessary as I've read elsewhere.slots
is not necessary in Qt5. Qt updated theconnect()
syntax to allow for connecting a signal to an arbitrary function, including lambdas. Because of this,slots
is not necessary. However, theslots
keyword still affects the way that an object'sQMetaObject
is built.moc
(aka, the "meta-object compiler") won't recognize a method as a slot unless it is within theslots:
section of a class definition. So, although the connection will still work, the method will not show up in introspection tools.