jeudi 5 juillet 2018

Qt How to return a subset of Q_PROPERTY from QObject

I want to extract a specific subset of defined properties from QObject classes.

This is my solution:

Name the subset of the properties with a specific prefix, for instance "param"

class MyObject: public QObject
{
   Q_OBJECT

   Q_PROPERTY(double paramX READ paramX WRITE setParamX NOTIFY paramXChanged)
   Q_PROPERTY(double paramY READ paramY WRITE setParamY NOTIFY paramYChanged)
   Q_PROPERTY(double paramZ READ paramZ WRITE setParamZ NOTIFY paramZChanged)

   // declaration etc...
};

to return the name of params for the object:

   MyObject* obj = new MyObject();  
   const QMetaObject* meta = obj->metaObject();

   QVector<QMetaProperty> list;
   for(int i=0; i<meta->propertyCount(); ++i)
   {
      QMetaProperty property = meta->property(i);
      QString name(property.name());
      if(name.startsWith("param"))
      {
         list.append(property);
      }
   }

with

   for(auto& e : list){
      qDebug() << e.name();
   }

the parameters are correctly printed.

However I don't really feel about this as a good approach, there's a better way of 1. organize the properties 2. return the properties list?

About (1) my solution doesn't really seems very robust and object-oriented About (2) maybe with a lambda I could reach the aim in a better/faster way?

Aucun commentaire:

Enregistrer un commentaire