PDA

View Full Version : how to avoid switch statements in item delegates



GrahamLabdon
9th March 2011, 11:49
Hi
I am implementing a Item Delegate for my tree based model.
I need to create a different editor depending upon the item being edited.
At the moment I am using switch statements to decide which editor to supply, but as my model grows so do the switch statements.



QWidget* editor;

QModelIndex parentIndex = index.model()->parent(index);

switch (index.model()->parent(index).row())
{
case 0:
{
switch (index.row())
{
case 0:
case 1:
{
editor = new QLineEdit(parent);
}
break;

case 2:
{
QStringList list;
Common::Enumerations::surveyUnits().getDisplayStri ngs(list);
editor = new QComboBox(parent);
((QComboBox*)editor)->addItems(list);
}
break;
}
}
break;

case 1:
{
editor = new QLineEdit(parent);
((QLineEdit*)editor)->setValidator(new QIntValidator());
}
break;
}
return editor;




Is there a better way to achieve this?

TIA

ChiliPalmer
9th March 2011, 21:11
How do you put the data into the model?
If it's a derivative of QAbstractItemModel you could use setData with your own DataRole to save a value from an enum, something like


enum EditorType {
LineEditEditor,
ComboBoxEditor,
...
}

Then you only need one switch