QDataWidgetMapper将一个数据库记录字段反映到其映射的窗口部件中,同时将窗口部件中所做出的更改反映回数据库,关键是关联一个model和一组widget
一、步骤
1、创建 QDataWidgetMapper 对象
2、关联 model
3、关联 widgets,并创建其与model中section的映射
4、定位到某个record
- QDataWidgetMapper *mapper = new QDataWidgetMapper;
- mapper->setModel(model);
- mapper->addMapping(mySpinBox, 0);
- mapper->addMapping(myLineEdit, 1);
- mapper->toFirst();
提交方式可以设为手动:
- mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
QComboBox组件的mapper比较特殊
第一种、在关系模型中实现mapper到QComboBox组件
- QSqlRelationalTableModel *model = QSqlRelationalTableModel(this);
-
- model->setTable("员工表");
- model->setRelation(dep_id,QSqlRelation("部门表","id","name"));
-
-
-
- QSqlTableModel *relationModel = model->relationModel(dep_id);
- comboBox->setMode(relationModel);
- comboBox->setModelColumn(relationModel->fieldIndex("name"));
第二种、使用代理的方式
1、实现自定义代理类,实现setEditorData()和setModelData()
2、给模型添加我们自己的代理类对象
- MapDelegate *delegate = new MapDelegate(this);
- mapper->setItemDelegate(delegate);
- void MapDelegate::setEditorData(QWidget *editor, const QModelIndex& index) const{
- if(index.column() == 0)
- {
- QComboBox *comboEditor = qobject_cast<QComboBox *>(editor);
- if (comboEditor)
- {
- int i = comboEditor->findText(index.model()->data(index, Qt::EditRole).toString());
- comboEditor->setCurrentIndex(i);
- }
- }
- else
- {
- return QItemDelegate::setEditorData(editor, index);
- }
- }
-
- void MapDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex& index) const
- {
- if(index.column() == 0)
- {
- QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
- if(comboBox)
- {
- model->setData(index, comboBox->currentText());
- }
- }
- else
- {
- return QItemDelegate::setModelData(editor, model, index);
- }
- }
posted on 2011-11-23 16:32
再生的雄鹰 阅读(4637)
评论(0) 编辑 收藏 引用