简述
模型视图架构提供了代理用来负责用户的交互。
简单的代理可以通过子类化QItemDelegate实现。如果子类化QItemDelegate无法满足要求,则应当考虑QAbstractItemDelegate。
代理所用的编辑器可以使用现成的输入控件,也可以直接处理events。
使用现成的代理类
Qt中的标准视图默认使用QItemDelegate来提供编辑功能。
所有的标准角色都由标准视图所采用的默认代理来处理。
itemDelegate()可以返回视图所使用的代理。setItemDelegate()可以设置自己想要的代理。
自定义代理类
构建表格模型
使用QStandardItemModel来构建表格模型,构建方法如下
QStandardItemModel *model = new QStandardItemModel(4, 4);
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 4; ++column) {
QStandardItem *item = new QStandardItem(QString("0"));
model->setItem(row, column, item);
}
}
实现自定义代理类
用QSpinBox来实现一个自定义代理类,使用效果如下所示
自定义代理类源码
.h
#ifndef SPINBOXDELEGATE_H
#define SPINBOXDELEGATE_H
#include <QStyledItemDelegate>
class SpinBoxDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
SpinBoxDelegate(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;
};
#endif // SPINBOXDELEGATE_H
.cpp
#include "spinboxdelegate.h"
#include <QSpinBox>
QWidget *SpinBoxDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QSpinBox *editor = new QSpinBox(parent);
editor->setFrame(false);
editor->setMinimum(0);
editor->setMaximum(100);
return editor;
}
void SpinBoxDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
int value = index.model()->data(index, Qt::EditRole).toInt();
QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
spinBox->setValue(value);
}
void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
spinBox->interpretText();
int value = spinBox->value();
model->setData(index, value, Qt::EditRole);
}
void SpinBoxDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
提示: 这里实现的几个函数都是来自QAbstractItemDelegate的虚函数。
当自定义代理类实现以后,可以通过如下方法使用:
SpinBoxDelegate *customDelegate = new SpinBoxDelegate;
table->setItemDelegate(customDelegate);
总结
在无用户交互的时候,代理并不会出现,当用户双击数据进行编辑的时候,代理就会出现。它的样式可以进行定制。只需要出现Qt所要求的几个接口便可以定制代理。
引用
[1] Qt助手