Frame::Frame(QWidget *parent) : QWidget(parent){sb = new QSpinBox(this);resize(60,60);}
SpinBoxDelegate::SpinBoxDelegate(QObject *parent) : QItemDelegate(parent){}QWidget *SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const{Frame *editor = new Frame(parent); editor->sb->setMinimum(0); editor->sb->setMaximum(100); return editor;}void SpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const{ int value = index.model()->data(index, Qt::EditRole).toInt(); Frame *frame = static_cast<Frame*>(editor); frame->sb->setValue(value);}void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const{ Frame *frame = static_cast<Frame*>(editor); frame->sb->interpretText(); int value = frame->sb->value(); model->setData(index, value, Qt::EditRole);}void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const{ editor->setGeometry(option.rect);}
QStandardItemModel model(4, 2); QTableView tableView; tableView.setModel(&model); SpinBoxDelegate delegate; tableView.setItemDelegate(&delegate); tableView.setEditTriggers(QAbstractItemView::AllEditTriggers); for (int row = 0; row < 4; ++row) { for (int column = 0; column < 2; ++column) { QModelIndex index = model.index(row, column, QModelIndex()); model.setData(index, QVariant((row+1) * (column+1))); } } tableView.setWindowTitle(QObject::tr("Spin Box Delegate")); tableView.show();