#include <QWidget>#include <QStyledItemDelegate>#include <QComboBox>#include <QModelIndex>#include <QObject>#include <QtSql>#include <QItemDelegate>class ComboBoxDelegate : public QItemDelegate{ Q_OBJECTpublic: ComboBoxDelegate(QObject *parent); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;};
#include "comboboxdelegate.h"#include <QComboBox>#include <QSqlQuery>#include <QDebug>ComboBoxDelegate::ComboBoxDelegate(QObject *parent) :QItemDelegate(parent){}QWidget *ComboBoxDelegate ::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const{ QComboBox* editor = new QComboBox(parent); QSqlQuery q; QStringList list; q.exec("select typname from pg_type");// while(q.next()){// QString name = q.value(1).toString();// list<<name;//}// editor->addItems(list); QSqlRecord rec = q.record(); while (q.next()) { editor->addItem(q.value(0).toString(), q.value(0)); } return editor;}void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const{ QComboBox *comboBox = static_cast<QComboBox*>(editor); QString value = index.model()->data(index, Qt::EditRole).toString(); comboBox->setCurrentIndex(comboBox->findText(value)); qDebug() << value;}void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{ QComboBox *comboBox = static_cast<QComboBox*>(editor); model->setData(index, comboBox->currentIndex(), Qt::EditRole);}void ComboBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const{ editor->setGeometry(option.rect);}
void Dialog::on_pushButton_clicked(){ int lastRow = model->rowCount(); model->insertRow(lastRow); model->setData(model->index(lastRow,1),""); tableNameColumn->selectRow(lastRow); tableNameColumn->setFocus(); ComboBoxDelegate* delegate = new ComboBoxDelegate(this); tableNameColumn->setItemDelegateForColumn(1, delegate); for ( int i = 0; i < model->insertRow(lastRow); ++i ) { tableNameColumn->openPersistentEditor(model->index(i, 1) ); } model->submit();}
void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{ QComboBox *comboBox = static_cast<QComboBox*>(editor); model->setData(index, comboBox->currentIndex(), Qt::EditRole);}