我能够使用 QStyledItemDelegate 在 QTreeView 中添加 QSpinBox 小部件。
QWidget *NoteDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (index.column() == 2)
{
QSpinBox *spinBox = new QSpinBox(parent);
spinBox->setRange(0, 9999);
return spinBox;
}
return QStyledItemDelegate::createEditor(parent, option, index);
}
void NoteDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if (index.column() == 2)
{
int value = index.model()->data(index, Qt::EditRole).toInt();
auto spinBox = static_cast<QSpinBox *>(editor);
spinBox->setValue(value);
return;
}
QStyledItemDelegate::setEditorData(editor, index);
}
void NoteDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
if (index.column() == 2)
{
auto spinBox = static_cast<QSpinBox *>(editor);
int value = spinBox->value();
model->setData(index, value, Qt::EditRole);
return;
}
QStyledItemDelegate::setModelData(editor, model, index);
}
但是,QSpinBox 只有在编辑模式下才会出现。即使处于显示模式,如何始终显示此 QSpinBox?