c++qtstaticqt5qproperty

How to use Q_PROPERTY with static class members


I'm new to Qt and came upon the Q_PROPERTY class, and was trying to set a static member using it. This is what I have so far:

class test{
      Q_OBJECT
      Q_PROPERTY(bool enabled READ enabled WRITE setEnabled)
    public:
    bool enabled() const{
        return m_enabled;
    }
    void setEnabled(bool enable){
        m_enabled = enable;
    }
    private:
    static bool m_enabled;
};

I'm getting compile errors when I try to run this so I'm not sure if there is a way to use static members with Q_PROPERTY. I've read through their documentation and other forum responses but I'm still unclear on the purpose of using Q_PROPERTY.


Solution

  • There's nothing special about using static members with Q_PROPERTY. There are two problems with the code that you provided:

    1. Your test class does not derive from QObject. Change it to this:
    class test: public QObject
    
    1. In your .cpp file, you need to define the instance of the static variable. This is true of any static members, not just for Q_PROPERTY. So in test.cpp, add this:
    bool test::m_enabled = false;
    

    With those changes, it should compile just fine.