Pergunta

I am not able to understand the usage of Q_PROPERTY. How th Q_PROPERTY helps in making a program defensive? What is it used for? I have seen the forum, but really not able to make its applicaton. I have understood the example, but not it's usage.

Here is the example, what do I gain with it. I understand that read will give a privilege of reading only.

The write property will give the privilege to write only. But what is the need of it? Can someone exemplify it?

 class MyClass : public QObject
 {
     Q_OBJECT
     Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged)
     Q_ENUMS(Priority)

 public:
     MyClass(QObject *parent = 0);
     ~MyClass();

     enum Priority { High, Low, VeryHigh, VeryLow };

     void setPriority(Priority priority)
     {
         m_priority = priority;
         emit priorityChanged(priority);
     }
     Priority priority() const
     { return m_priority; }

 signals:
     void priorityChanged(Priority);

 private:
     Priority m_priority;
 };
Foi útil?

Solução

It has the following advantages:

  • It is available for the meta object system, so it can be introspected, used from QML etc.

  • It has further options than just read and write. Look at notify, reset, etc. It is also easier to integrate them into QtCreator (designer).

  • You do not need to write the boilerplate with Qt 5.1 onwards in common read and write cases because they will be generated for you.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top