#ifndef SPINBOXDELEGATE_H #define SPINBOXDELEGATE_H #include <QItemDelegate> class SpinBoxDelegate : public QItemDelegate { Q_OBJECT public: explicit SpinBoxDelegate(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; signals: public slots: }; #endif // SPINBOXDELEGATE_H
sinboxdelegate.cpp函數
#include "spinboxdelegate.h" #include <QSpinBox> SpinBoxDelegate::SpinBoxDelegate(QObject *parent) : QItemDelegate(parent) { } QWidget* SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QSpinBox *editor = new QSpinBox(parent); editor->setMaximum(100); editor->setMinimum(0); return editor; } void SpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QSpinBox *spinBox = static_cast<QSpinBox *>(editor); spinBox->interpretText(); int num = index.data(Qt::DisplayRole).toInt(); spinBox->setValue(num); } void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QSpinBox *spinBox = static_cast<QSpinBox *>(editor); int num = spinBox->value(); model->setData(index, QVariant(num), Qt::EditRole); } void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { editor->setGeometry(option.rect); }
main.cppspa
#include <QTableView> #include <QStandardItemModel> #include <QModelIndex> #include <QApplication> #include <spinboxdelegate.h> int main(int argc, char *argv[]) { QApplication a(argc, argv); QStandardItemModel *standardModel = new QStandardItemModel(4,2); QTableView *tableView = new QTableView; tableView->setModel(standardModel); for(int row = 0; row < 4; row++) { for(int col = 0; col < 2; col++) { QModelIndex index = standardModel->index(row, col, QModelIndex()); standardModel->setData(index, QVariant((row+1)*(col+1))); } } SpinBoxDelegate *delegate = new SpinBoxDelegate; tableView->setItemDelegate(delegate); tableView->show(); return a.exec(); }
程序效果以下:3d