Reputation: 6171
Given the following:
struct Property {
QWidget *label;
QWidget *field;
};
QList<Property*> properties;
In which most of the field
s are QLineEdit
s but some are QTimeEdit
s 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 field
s 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
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
Reputation: 949
There are multiple ways of doing that.
p->metaObject()->className()
method.qobject_cast<Class*>(p)
for all possible types. The one that is not NULL is the right type.p->inherits("CLASS")
to ask for inheritance.Upvotes: 1