上一章节中的不足是需要进入编辑模式才能显示数据(即双击才能展示),但是真实的项目中需要默认需要展示数据的。需要实现paint函数和setmodel的时候设置自定义数据代码全部如下
CustomParamViewDelegate.cpp
#include "CustomParamViewDelegate.h"
CustomParamViewDelegate::CustomParamViewDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
CustomParamViewDelegate::~CustomParamViewDelegate()
{
}
QWidget* CustomParamViewDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
int type = index.data(Qt::UserRole).toInt();
switch (type) {
case (CustomParamViewDelegate::Type_ComboBox): {
return new QComboBox(parent);
}
case (CustomParamViewDelegate::Type_Label): {
return new QLabel(parent);
}
case (CustomParamViewDelegate::Type_LinEdit): {
return new QLineEdit(parent);
}
default:
break;
}
return nullptr;
}
void CustomParamViewDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
int type = index.data(Qt::UserRole).toInt();
//QString data = index.data().toString();
QString data = index.data(Qt::UserRole + 1).toString();
switch (type) {
case (CustomParamViewDelegate::Type_ComboBox): {
QComboBox* cob = static_cast<QComboBox*>(editor);
QStringList strList = data.split(",");
cob->