QDataWidgetMapper將一個數(shù)據(jù)庫記錄字段反映到其映射的窗口部件中,同時將窗口部件中所做出的更改反映回?cái)?shù)據(jù)庫,關(guān)鍵是關(guān)聯(lián)一個model和一組widget
一、步驟
1、創(chuàng)建 QDataWidgetMapper 對象
2、關(guān)聯(lián) model
3、關(guān)聯(lián) widgets,并創(chuàng)建其與model中section的映射
4、定位到某個record
- QDataWidgetMapper *mapper = new QDataWidgetMapper;
- mapper->setModel(model);
- mapper->addMapping(mySpinBox, 0);
- mapper->addMapping(myLineEdit, 1);
- mapper->toFirst();
提交方式可以設(shè)為手動:
- mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
QComboBox組件的mapper比較特殊
第一種、在關(guān)系模型中實(shí)現(xiàn)mapper到QComboBox組件
- QSqlRelationalTableModel *model = QSqlRelationalTableModel(this);
-
- model->setTable("員工表");
- model->setRelation(dep_id,QSqlRelation("部門表","id","name"));
- // ... 其它代碼
-
- //QComboBox與QListWidget很相擬,因?yàn)樗幸粋€內(nèi)部模型去保存它的數(shù)據(jù)條目,所以我們用自己建的模型代替那個自帶的模型。給出QSqlRelationalTableModel使用的關(guān)系模型,這個模型有兩列,必須指出組合框應(yīng)該顯示哪一列
- QSqlTableModel *relationModel = model->relationModel(dep_id); // 部門ID
- comboBox->setMode(relationModel);
- comboBox->setModelColumn(relationModel->fieldIndex("name")); // 使用字段名得到正確的標(biāo)題索引,以使組合框顯示部門名
第二種、使用代理的方式
1、實(shí)現(xiàn)自定義代理類,實(shí)現(xiàn)setEditorData()和setModelData()
2、給模型添加我們自己的代理類對象
- MapDelegate *delegate = new MapDelegate(this); // 生成自定義的代理類對象
- mapper->setItemDelegate(delegate); // 給模型添加我們自己的代理類
- void MapDelegate::setEditorData(QWidget *editor, const QModelIndex& index) const{
- if(index.column() == 0) // 假如模型的第0列為公司名
- {
- QComboBox *comboEditor = qobject_cast<QComboBox *>(editor);
- if (comboEditor)
- {
- int i = comboEditor->findText(index.model()->data(index, Qt::EditRole).toString()); // 在comboBox組件中查找model中的當(dāng)前公司名
- comboEditor->setCurrentIndex(i); // 設(shè)成model中的當(dāng)前公司名
- }
- }
- 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);
- }
- }