Justin
Justin

Reputation: 2372

Qt "private slots:" what is this?

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);

 ...

Upvotes: 101

Views: 61137

Answers (4)

KcFnMi
KcFnMi

Reputation: 6161

If we are going to call slots using the connect mechanism, then we declare them as public slots.

If we are not going to call them using the connect mechanism, then we do not declare them as slots.

If we are considering to call them both ways, may be its time for refactoring to fit in previous cases.

That's how I used to think.

Throughout the Qt documentation I see them as public. Just spot one place though where private slots are mentioned

Note: You need to include the QTest header and declare the test functions as private slots so the test framework finds and executes it.

Upvotes: 1

Euri Pinhollow
Euri Pinhollow

Reputation: 342

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

Upvotes: 4

Russell Davis
Russell Davis

Reputation: 8517

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.

Upvotes: 61

Andrew
Andrew

Reputation: 24846

The keywords such as public, private are ignored for Qt slots. All slots are actually public and can be connected

Upvotes: 23

Related Questions