代理作用:在界面发生编辑时可以指定编辑所用的组件,可以沟通Model和View
自定义代理需要继承的基类和需要实现的方法
使用步骤:
- 继承QStyledItemDelegate,实现上面的四个方法
- 在页面上声明一个继承后类的对象
- 类似代码
ui->tableView->setItemDelegateForColumn(0, intSpinDelegate);
为某行、某列、某个单元格设置
例子:本例子中只展示修改的内容,其他代码同上节标准模型代码
QIntDelegate.h
#ifndef QINTDELEGATE_H
#define QINTDELEGATE_H
#include <QObject>
#include <QStyledItemDelegate>
class QIntDelegate : public QStyledItemDelegate
{
public:
QIntDelegate();
QIntDelegate(QWidget *parent = nullptr);
// QAbstractItemDelegate interface
public:
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;//生成一个editor
void setEditorData(QWidget *editor, const QModelIndex &index) const override;//设置editor数据,供编辑
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override;//设置model数据,View数据写回model
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override;//设置editor的尺寸
};
#endif // QINTDELEGATE_H
QIntDelegate.cpp
#include "QIntDelegate.h"
#include <QSpinBox>
QIntDelegate::QIntDelegate()
{
}
QIntDelegate::QIntDelegate(QWidget *parent)
{
this->setParent(parent);
}
QWidget *QIntDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const//生成一个editor
{
QSpinBox *editorSpin = new QSpinBox(parent);
editorSpin->setMinimum(0);
editorSpin->setFrame(false);//设置边框
return editorSpin;
}
void QIntDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const//设置editor数据,供编辑
{
int data = index.model()->data(index, Qt::EditRole).toInt();//从index反向拿到model,然后拿到数据
QSpinBox *spinBox = qobject_cast<QSpinBox *>(editor);
spinBox->setValue(data);
}
void QIntDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const//设置model数据,View数据写回model
{
QSpinBox *spinBox = qobject_cast<QSpinBox *>(editor);
spinBox->interpretText();//可以保证拿到的是最新的值
int val = spinBox->value();
model->setData(index, val, Qt::EditRole);
}
void QIntDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const//设置editor的尺寸
{
editor->setGeometry(option.rect);
}
mainwindow中添加的内容
/**==================== 自定义代理新增内容 =========================**/
QIntDelegate *intSpinDelegate = new QIntDelegate(this);
QQualityComboboxDelegate *qualityEditor = new QQualityComboboxDelegate();
/**==================== 自定义代理新增内容 =========================**/
ui->tableView->setItemDelegateForColumn(0, intSpinDelegate);
ui->tableView->setItemDelegateForColumn(4, qualityEditor);
标签:index,QT5,const,自定义,22,editor,QWidget,model,QIntDelegate
From: https://www.cnblogs.com/echo-lovely/p/17221489.html