The definition of the delegate is as follows:
#ifndef COMBODELEGATE_H
#define COMBODELEGATE_H
#include <QItemDelegate>
class ComboDelegate : public QItemDelegate
{
Q_OBJECT
public:
explicit ComboDelegate(const QStringList &items, QObject *parent = 0);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
void setEditorData(QWidget *editor, const QModelIndex &index) const override;
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const override;
void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &index) const override;
signals:
private:
QStringList myItems;
};
#endif // COMBODELEGATE_H
The implementation of the delegate is as follows:
#include "combodelegate.h"
#include <QtWidgets/QComboBox>
#include <QDebug>
ComboDelegate::ComboDelegate(const QStringList &items, QObject *parent) : QItemDelegate(parent)
{
myItems=items;
}
QWidget *ComboDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(option)
QComboBox *editor = new QComboBox(parent);
editor->addItems(myItems);
editor->setEditable(false);
return editor;
}
void ComboDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::EditRole).toString();
QComboBox *comboBox = static_cast<QComboBox*>(editor);
int icurIndex = comboBox->findText(value);
// qDebug()<<"value:"<<value;
if(icurIndex<0)
{
comboBox->setCurrentText(value);
}
else
{
comboBox->setCurrentIndex(icurIndex);
}
}
void ComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
QString value = comboBox->currentText();
if(value.isEmpty())
{
value=QString::number(0);
}
model->setData(index, value, Qt::EditRole);
}
void ComboDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
QComboBox *comboBox = static_cast<QComboBox*>(editor);
comboBox->showPopup(); // 直接弹出下拉框,没有这一句双击后需要再点一次Combox才会弹出下拉框
}
the examples is as follows:
我们写一个main函数,使用一下ComboDelegate,演示该类如何使用
#include <QApplication>
#include<QStandardItemModel>
#include<QTableView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableView tableView;
QStandardItemModel itemModel(3,2,&tableView);
tableView.setModel(&itemModel);
QStringList strList;
strList<<"com1"<<"com2"<<"com3";
tableView.setItemDelegateForColumn(0,new ComboDelegate(strList,&tableView));
tableView.setItemDelegateForColumn(1,new ComboDelegate(strList,&tableView));
tableView.resize(300,200);
tableView.show();
return a.exec();
}