0

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.

programmer
  • 27
  • 4
  • 3
    `I'm getting compile errors` - don't you think it would be interesting for us to know which compile errors you get? I would guess you don't get compile errors but linker errors. – chehrlic Mar 22 '21 at 15:45
  • Missing QObject parent ? – levif Mar 22 '21 at 15:47

2 Answers2

1

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.

JarMan
  • 7,589
  • 1
  • 10
  • 25
0

Your class is going to need to inherit from QObject in order to use things such as Q_PROPERTY (class test : public QObject).

Q_PROPERTY is used to declare properties that can then interop with Qt's meta-object system. For example, you can set the property via the string name of the property, can interface with the property through QML, can animate the property using QPropertyAnimation, and Q_PROPERTY can be used to define properties that will show up within editors such as Qt Designer. Generally, a standard C++/Qt application will not need Q_PROPERTY.

Dean Johnson
  • 1,682
  • 7
  • 12