Hello!

I’m implementing an item delegate to extend the QStyledItemDelegate. The idea is whe an value is a QStringList i use a QComboBox as editor in the item delegate. But i have some problems

1. When i set the QStringList in the data of a view (lets say a tree), the cell doesn’t show a text. When i double click the cell a combobox appears, i can make a selection, the combobox closes and nothin is diplayed in the cell

2. When i want to know what is the selection i can’t figure ir out how to get the item selected in the QComboBox.

Any ideas?

Qt Code:
  1. class ItemDelegate : public QStyledItemDelegate {
  2. Q_OBJECT
  3.  
  4. public:
  5. ItemDelegate(QObject *parent = 0): QStyledItemDelegate(parent) {;}
  6. virtual ~ItemDelegate() { ; }
  7.  
  8. QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
  9. const QModelIndex &index) const;
  10.  
  11. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  12.  
  13. void setModelData(QWidget *editor, QAbstractItemModel *model,
  14. const QModelIndex &index) const;
  15.  
  16. inline void updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex& ) const {
  17. editor->setGeometry(option.rect);
  18. }
  19.  
  20. };
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. QWidget* ItemDelegate::createEditor(QWidget *parent,
  2. const QStyleOptionViewItem & option ,
  3. const QModelIndex & index ) const {
  4.  
  5. QVariant data = index.model()->data(index, Qt::EditRole);
  6.  
  7. QWidget* editor;
  8. switch( data.type() ) {
  9. case QVariant::StringList:
  10. editor = new QComboBox(parent);
  11. dynamic_cast<QComboBox*>(editor)->setFrame(false);
  12. break;
  13. default:
  14. editor = QStyledItemDelegate::createEditor(parent, option, index);
  15. }
  16.  
  17. return editor;
  18. }
  19.  
  20. void ItemDelegate::setEditorData(QWidget *editor,
  21. const QModelIndex &index) const {
  22.  
  23. QVariant data = index.model()->data(index, Qt::EditRole);
  24.  
  25. switch( data.type() ) {
  26. case QVariant::StringList:
  27. static_cast<QComboBox*>(editor)->addItems(data.toStringList());
  28. break;
  29. default:
  30. QStyledItemDelegate::setEditorData(editor, index);
  31. }
  32. }
  33.  
  34. void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
  35. const QModelIndex &index) const
  36. {
  37. QVariant data = index.model()->data(index, Qt::EditRole);
  38.  
  39. switch( data.type() ) {
  40. case QVariant::StringList: {
  41. for( int i = 0; i < static_cast<QComboBox*>(editor)->count(); ++i )
  42. list << static_cast<QComboBox*>(editor)->itemText(i);
  43. model->setData(index, QVariant(list), Qt::EditRole);
  44. break;
  45. }
  46. default:
  47. QStyledItemDelegate::setModelData(editor, model, index);
  48. }
  49. }
To copy to clipboard, switch view to plain text mode