自定义代理编辑控件是在tableView单元格中,呈现编辑辅助的Combox控件
自定义代理编辑控件类TComboBoxDelegate的定义过程
重写自定义代理编辑组件类的四个方法: 创建编辑组件、模型赋值给代理编辑组件、代理编辑组件数据到模型、更新位置
.h
#ifndef TCOMBOBOXDELEGATE_H
#define TCOMBOBOXDELEGATE_H
#include <QObject>
#include <QStyledItemDelegate>
class TComboBoxDelegate : public QStyledItemDelegate
{
Q_OBJECT
private:
QStringList m_itemList;
bool m_editable;
public:
explicit TComboBoxDelegate(QObject *parent = nullptr);
void setItems(QStringList items,bool editable);
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
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;
};
#endif // TCOMBOBOXDELEGATE_H
.cpp
#include "tcomboboxdelegate.h"
#include <QComboBox>
TComboBoxDelegate::TComboBoxDelegate(QObject *parent)
: QStyledItemDelegate{parent}
{
}
void TComboBoxDelegate::setItems(QStringList items, bool editable)
{
m_itemList= items;
m_editable = editable;
}
QWidget *TComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(option);
Q_UNUSED(index);//不需要 option 和index 参数
QComboBox *editor = new QComboBox(parent);
editor->setEditable(m_editable);
for(int i=0;i<m_itemList.count();i++)
{
editor->addItem(m_itemList.at(i));
}
return editor;
}
void TComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString str= index.model()->data(index,Qt::EditRole).toString();
QComboBox *combo = static_cast<QComboBox*>(editor);
combo->setCurrentText(str);
}
void TComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QComboBox *combo = static_cast<QComboBox*>(editor);
QString str = combo->currentText();
model->setData(index,str,Qt::EditRole);
}
void TComboBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(index);
editor->setGeometry(option.rect);
}
TComBoxDelegate自定义编辑控件
总结
1. 统一继承自 QStyledItemDelegate
2. 根据Combox的特性,需要自定义QStringList ,是否可编辑