2 #include <QSqlQueryModel>
3 #include "comboboxdelegate.h"
4 #include "emufrontquerymodel.h"
5 #include "emufrontobject.h"
7 ComboBoxDelegate::ComboBoxDelegate(QSqlQueryModel *cbmodel, int cbmodelIdColumn, int cbmodelDisplayColumn, QWidget *parent) :
8 QStyledItemDelegate(parent), cbmodel(cbmodel), cbmodelIdColumn(cbmodelIdColumn), cbmodelDisplayColumn(cbmodelDisplayColumn)
11 void ComboBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
13 // get the item id from the hosting view's model
14 int objid = index.model()->data(index, Qt::DisplayRole).toInt();
16 // find matching object from QComboBox's model
17 QModelIndex startInd = cbmodel->index(0, cbmodelIdColumn);
18 QModelIndexList indList = cbmodel->match(startInd, Qt::DisplayRole, objid);
19 QModelIndex ind = indList.empty() ?
21 cbmodel->index(indList.first().row(), cbmodelDisplayColumn);
23 QString txt = ind.isValid() ?
24 cbmodel->data(ind).toString() : "";
27 painter->drawText(option.rect, txt);
31 //QSize ComboBoxDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { }
33 QWidget* ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
35 QComboBox *editor = new QComboBox(parent);
36 editor->setEditable(false);
37 editor->setModel(cbmodel);
38 editor->setModelColumn(cbmodelDisplayColumn);
39 connect(editor, SIGNAL(currentIndexChanged(int)), this, SLOT(commitAndCloseEditor(int)));
43 void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
45 // set the correct item selected for the editor:
46 // get the item id from the parent view's model
47 int id = index.model()->data(index, Qt::DisplayRole).toInt();
48 QComboBox *cbox = qobject_cast<QComboBox *>(editor);
49 // create a start index from combobox model
50 QModelIndex startInd = cbmodel->index(0, cbmodelIdColumn);
51 // search an index for selected item in parent view
52 QModelIndexList indList = cbmodel->match(startInd, Qt::DisplayRole, id);
53 // if no match set no item selected
54 int ind = indList.empty() ? -1 : indList.first().row();
55 cbox->setCurrentIndex(ind);
58 void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
60 QComboBox *cbox = qobject_cast<QComboBox *>(editor);
61 if (cbox->currentIndex() == -1) return;
62 QModelIndex mi = cbmodel->index(cbox->currentIndex(), cbmodelIdColumn);
63 int id = cbmodel->data(mi).toInt();
64 model->setData(index, id);
67 void ComboBoxDelegate::commitAndCloseEditor(int)
69 QComboBox *editor = qobject_cast<QComboBox *>(sender());
70 emit commitData(editor);
71 emit closeEditor(editor);