直接堆代码
头文件inputDelegate.h
class InputDelegate: public QItemDelegate
{
Q_OBJECT
public:
explicit InputDelegate(QObject *parent = nullptr);
//第1步:创建一个widget作为编辑器
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,const QModelIndex &index) const;
//第2步:初始化显示数据
void setEditorData(QWidget *editor, const QModelIndex &index) const ;
//第3步:用户完成编辑、编辑器被关闭时,提供数据到model
void setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const ;
//第4步:调用编辑器的显示位置
void updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
inputdelegate.cpp实现
InputDelegate::InputDelegate(QObject *parent) : QItemDelegate(parent)
{
}
QWidget *InputDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const
{
QLineEdit *pEditor = new QLineEdit(parent);
return pEditor;
}
void InputDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString text = index.model()->data(index, Qt::DisplayRole).toString();
QLineEdit *lineEdit = static_cast(editor);
lineEdit->setText(text);
}
void InputDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QLineEdit *lineEdit = static_cast(editor);
QString text = lineEdit->text();
model->setData(index, text, Qt::EditRole);
}
void InputDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}