QTableView自定义代理(三):基于QDoubleSpinBox的自定义代理类
- 头文件
#include <QStyledItemDelegate>
class QMyDoubleSpinDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
QMyDoubleSpinDelegate (QObject *parent=0);
//自定义代理组件必须继承以下4个函数
//创建编辑组件
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const Q_DECL_OVERRIDE;
void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const Q_DECL_OVERRIDE;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
const QModelIndex &index) const Q_DECL_OVERRIDE;
};
- 源文件
#include "qmydoublespindelegate.h"
#include <QDoubleSpinBox>
QMyDoubleSpinDelegate ::QMyDoubleSpinDelegate (QObject *parent):QStyledItemDelegate(parent)
{
}
QWidget *QMyDoubleSpinDelegate ::createEditor(QWidget *parent,
const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(option);
Q_UNUSED(index);
QDoubleSpinBox *editor = new QDoubleSpinBox(parent);
editor->setFrame(false);
editor->setMinimum(0);
editor->setDecimals(2);
editor->setMaximum(10000);
return editor;
}
void QMyDoubleSpinDelegate ::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
float value = index.model()->data(index, Qt::EditRole).toFloat();
QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
spinBox->setValue(value);
}
void QMyDoubleSpinDelegate ::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
spinBox->interpretText();
float value = spinBox->value();
QString str=QString::asprintf("%.2f",value);
model->setData(index, str, Qt::EditRole);
}
void QMyDoubleSpinDelegate ::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
- 使用方法
QMyDoubleSpinDelegate *doubleSpinDelegate = new QMyDoubleSpinDelegate(this) ;
ui->tableView->setItemDelegateForColumn(2, doubleSpinDelegate); // 给需要的列设置代理