KcFnMi
KcFnMi

Reputation: 6171

Collecting values from form's widgets

Given the following:

struct Property {
  QWidget *label;
  QWidget *field;
};
QList<Property*> properties;

In which most of the fields are QLineEdits but some are QTimeEdits and might be other kinds, like QDateEdit.

This is used to (conveniently) make a form this way:

for(int i = 0; i != properties.size(); i++)
    formLayout->addRow( properties.at(i)->label,properties.at(i)->field );

And I'm thinking in collect the values from the form's fields in the same fashion:

foreach (const Property *p, properties) 
    p->field->value()

The problem is there is no such value() function.

Is this design ok? Which should be the approach in order to achieve the value()?

Upvotes: 0

Views: 37

Answers (2)

peppe
peppe

Reputation: 22796

The naïve approach is hardcoding all the possibilities in advance, by employing something like:

if (QLineEdit *le = qobject_cast<QLineEdit *>(obj)) {
    le->text(); 
} else if (QDateTimeEdit *dte = qobject_cast<QDateTimeEdit *>(obj)) {
    dte->dateTime();
} else if (...) { // repeat for all the cases

}

The proper and robust approach is exploiting Qt's meta object capabilities. In particular, a class can mark one of its properties to be the USER property, that is, the property that the user interacts with. This is done for Qt's own edit widgets.

So the good and general way is:

QVariant result;
QMetaObject *mo = obj->metaObject();
const int propertyCount = mo->propertyCount();
for (int i = 0; i < propertyCount; ++i) {
    QMetaProperty mp = mo->property(i);
    if (mp.isUser(obj)) { 
        result = mp.read(obj);
        break;
    }
}
// use result

Upvotes: 0

OnWhenReady
OnWhenReady

Reputation: 949

There are multiple ways of doing that.

  1. An ugly approach would be to use the p->metaObject()->className() method.
  2. A better way is to use qobject_cast<Class*>(p) for all possible types. The one that is not NULL is the right type.
  3. You could use p->inherits("CLASS") to ask for inheritance.

Upvotes: 1

Related Questions