QDataWidgetMapper类

来源:互联网 发布:运维工程师要编程吗 编辑:程序博客网 时间:2024/04/30 17:05

  QDataWidgetMapper将一个数据库记录字段反映到其映射的窗口部件中,同时将窗口部件中所做出的更改反映回数据库,关键是关联一个model和一组widget
一、步骤

1、创建 QDataWidgetMapper 对象
2、关联 model
3、关联 widgets,并创建其与model中section的映射
4、定位到某个record

[cpp] view plaincopyprint?
  1. QDataWidgetMapper *mapper = new QDataWidgetMapper;
  2. mapper->setModel(model);
  3. mapper->addMapping(mySpinBox, 0);
  4. mapper->addMapping(myLineEdit, 1);
  5. mapper->toFirst();


提交方式可以设为手动:

[cpp] view plaincopyprint?
  1. mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);


QComboBox组件的mapper比较特殊

第一种、在关系模型中实现mapper到QComboBox组件

[cpp] view plaincopyprint?
  1. QSqlRelationalTableModel *model = QSqlRelationalTableModel(this);
  2. model->setTable("员工表");
  3. model->setRelation(dep_id,QSqlRelation("部门表","id","name"));
  4. // ... 其它代码
  5. //QComboBox与QListWidget很相拟,因为它有一个内部模型去保存它的数据条目,所以我们用自己建的模型代替那个自带的模型。给出QSqlRelationalTableModel使用的关系模型,这个模型有两列,必须指出组合框应该显示哪一列
  6. QSqlTableModel *relationModel = model->relationModel(dep_id); // 部门ID
  7. comboBox->setMode(relationModel);
  8. comboBox->setModelColumn(relationModel->fieldIndex("name"));// 使用字段名得到正确的标题索引,以使组合框显示部门名

第二种、使用代理的方式

1、实现自定义代理类,实现setEditorData()和setModelData()

2、给模型添加我们自己的代理类对象

[cpp] view plaincopyprint?
  1. MapDelegate *delegate = new MapDelegate(this);// 生成自定义的代理类对象
  2. mapper->setItemDelegate(delegate); // 给模型添加我们自己的代理类
[cpp] view plaincopyprint?
  1. void MapDelegate::setEditorData(QWidget *editor,const QModelIndex& index) const{
  2. if(index.column() == 0) // 假如模型的第0列为公司名
  3. {
  4. QComboBox *comboEditor = qobject_cast<QComboBox *>(editor);
  5. if (comboEditor)
  6. {
  7. int i = comboEditor->findText(index.model()->data(index, Qt::EditRole).toString());// 在comboBox组件中查找model中的当前公司名
  8. comboEditor->setCurrentIndex(i); // 设成model中的当前公司名
  9. }
  10. }
  11. else
  12. {
  13. return QItemDelegate::setEditorData(editor, index);
  14. }
  15. }
  16. void MapDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex& index) const
  17. {
  18. if(index.column() == 0)
  19. {
  20. QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
  21. if(comboBox)
  22. {
  23. model->setData(index, comboBox->currentText());
  24. }
  25. }
  26. else
  27. {
  28. return QItemDelegate::setModelData(editor, model, index);
  29. }
  30. }  
  31. http://blog.csdn.net/reborntercel/article/details/7004278