1.介绍
在使用Table时,我们希望可以对table做更好的个性化处理。例如需要美化表格,在表格中添加控件等等。这时候就要用到Delegate了。说白了,Delegate就在在数据和界面之间增加了一层渲染,处理的功能。
2.QStyledItemDelegate
QT提供了两个基类QStyleDelegate 和QStyledItemDelegate为我们提供自定义Delegate,QStyleDelegate 在QT4.4之前用得比较多,在QT4.4之后基本上都在使用QStyledItemDelegate。 我们通过子类化QStyledItemDelegate实现自定义,并重新实现paint(),可能还有sizeHint()。paint()函数为每个item单独调用,使用sizeHint(),可以为每个item指定提示。(这两个函数对表格的美化)。 如果我们需要在表格中添加一些控件,像Button。。。等我们就需要实现以下四个函数 : createEditor()返回用于从模型更改数据的控件,可以重新实现该控件来定制编辑行为。 setEditorData()为控件提供了要操作的数据。 updateEditorGeometry()确保编辑器相对于item视图正确显示。 setModelData()将更新后的数据返回给模型。
3.代码
delegate.h
class ButtonDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
ButtonDelegate(QObject *parent = 0);
//index是表中的item索引,可以获取表中item的相关信息。
//option可以获得表格中格子的大小,位置。。等信息
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
void paint(QPainter *painter,
const QStyleOptionViewItem &option, const QModelIndex &index) const;
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
//editor就是自定义控件
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;
};
delegate.cc
#include "ui_button_delegate.h"
QWidget *ButtonDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (index.row() % 2)
{
QPushButton* box = new QPushButton(parent);
box->setText("Delete");
return box;
}
else
{
QLineEdit *lineEdit = new QLineEdit(parent);
return lineEdit;
}
}
void ButtonDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
}
void ButtonDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
}
void ButtonDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
ButtonDelegate::ButtonDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
QSize ButtonDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(10, 10);
}
void ButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (!index.isValid() || option.state == QStyle::State_None || !index.isValid())
return;
if (index.row() % 2)
{
painter->fillRect(option.rect, QColor(Qt::red));
}
else
{
painter->fillRect(option.rect, QColor(Qt::yellow));
}
}
效果: