Combo Boxes in Item Views
Sample code to use combo boxes as editor widgets in an item view or item widget.
The delegate creates a combo box if the index is in the second column of a list view. For the other columns it just returns the default editor, that QStyledItemDelegate [doc.qt.nokia.com] creates.
File itemdelegate.h
- // ----- File itemdelegate.h -----
- #ifndef ITEMDELEGATE_H
- #define ITEMDELEGATE_H
- #include <QStyledItemDelegate>
- {
- Q_OBJECT
- public:
- ~ComboBoxItemDelegate();
- virtual QWidget *createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const;
- virtual void setModelData ( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const;
- };
- #endif // ITEMDELEGATE_H
File itemdelegate.cpp
- // ----- File itemdelegate.cpp -----
- #include "itemdelegate.h"
- #include <QComboBox>
- {
- }
- ComboBoxItemDelegate::~ComboBoxItemDelegate()
- {
- }
- QWidget* ComboBoxItemDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const
- {
- // ComboBox ony in column 2
- if(index.column() != 1)
- // Create the combobox and populate it
- int row = index.row();
- return cb;
- }
- {
- // get the index of the text in the combobox that matches the current value of the itenm
- int cbIndex = cb->findText(currentText);
- // if it is valid, adjust the combobox
- if(cbIndex >= 0)
- cb->setCurrentIndex(cbIndex);
- } else {
- }
- }
- void ComboBoxItemDelegate::setModelData ( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const
- {
- // save the current text of the combo box as the current value of the item
- else
- }
File main.cpp
- // ----- File main.cpp -----
- #include <QApplication>
- #include <QTableWidget>
- #include "itemdelegate.h"
- int main(int argc, char *argv[])
- {
- QTableWidget tw;
- ComboBoxItemDelegate *cbid = new ComboBoxItemDelegate(&tw);
- tw.setItemDelegate(cbid);
- tw.setColumnCount(4);
- tw.setRowCount(10);
- tw.resize(600,400);
- tw.show();
- return a.exec();
- }

