//delete.h #ifndef DELEGATE_H #define DELEGATE_H #include<QItemDelegate> #include<QModelIndex> #include<QObject> #include<QSize> #include<QSpinBox> #include<QWidget> class Delegate : public QItemDelegate { Q_OBJECT public: explicit Delegate(QObject *parent = 0); 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 // DELEGATE_H
//dialog.h #ifndef DIALOG_H #define DIALOG_H #include"delegate.h" #include <QDialog> #include<QtCore> #include<QtGui> #include<QModelIndex> #include<QStandardItemModel> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private: Ui::Dialog *ui; QStandardItemModel *model; Delegate *mydelegate; }; #endif // DIALOG_H
//delegate.cpp #include "delegate.h" Delegate::Delegate(QObject *parent):QItemDelegate(parent) { } QWidget *Delegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QSpinBox *editor = new QSpinBox(parent); editor->setMinimum(0); editor->setMaximum(100); return editor; } void Delegate::setEditorData(QWidget *editor, const QModelIndex &index) const { int value = index.model()->data(index,Qt::EditRole).toInt(); QSpinBox *spinbox = static_cast<QSpinBox*>(editor); spinbox->setValue(value); } void Delegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QSpinBox *spinbox = static_cast<QSpinBox*>(editor); spinbox->interpretText(); int value = spinbox->value(); model->setData(index,value,Qt::EditRole); } void Delegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { editor->setGeometry(option.rect); }
//dialog.cpp #include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); mydelegate = new Delegate(this); model = new QStandardItemModel(4,2,this); for(int row = 0; row < 4; ++row) { for(int col = 0; col < 2; ++col) { QModelIndex index = model->index(row,col,QModelIndex()); model->setData(index,0); } } ui->tableView->setModel(model); ui->tableView->setItemDelegate(mydelegate); } Dialog::~Dialog() { delete ui; }
//main.cpp #include "dialog.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Dialog w; w.show(); return a.exec(); }