委托(QItemDelegate/QStyledItemDelegate)的功能很强大,可以把控件设置成只读、表格的某一列设置成各种自己想要的控件
--------------
定义自己的Delegate:
class MyDelegate: public QStyledItemDelegate
{
//创建你编辑时候的控件
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
//编辑的时候设置数据到上面创建的editor中。
void setEditorData(QWidget *editor, const QModelIndex &index) const;
//编辑完成,保存数据到data中
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
//设置编辑控件的位置和大小、样式等
void updateEditorGeometry ( QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index ) const;
}
其中,QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;这个方法里创建你编辑时候需要的控件~
view->setItemDelegate(....自己定义的delegate)... //view可以是listView,tableView
/**把表格的第一列设置成只读,ReadOnlyDelegate()为自己定义的,继承QItemDelegate(parent)**/
tableView->setItemDelegateForColumn(0, new ReadOnlyDelegate(this));
/**把表格的第四列设置成spinBox,SettingValueDelegate()自己定义的,继承QItemDelegate(parent)**/
tableView->setItemDelegateForColumn(3, new SettingValueDelegate(this));