QT筆記:資料庫總結(五)之SQL模型類-QDataWidgetMapper類

來源:互聯網
上載者:User

     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")); // ... 其它代碼//QComboBox與QListWidget很相擬,因為它有一個內部模型去儲存它的資料條目,所以我們用自己建的模型代替那個內建的模型。給出QSqlRelationalTableModel使用的關聯式模式,這個模型有兩列,必須指出組合框應該顯示哪一列QSqlTableModel *relationModel = model->relationModel(dep_id); // 部門IDcomboBox->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) // 假如模型的第0列為公司名    {        QComboBox *comboEditor = qobject_cast<QComboBox *>(editor);        if (comboEditor)        {            int i = comboEditor->findText(index.model()->data(index, Qt::EditRole).toString()); // 在comboBox組件中尋找model中的當前公司名   comboEditor->setCurrentIndex(i); // 設成model中的當前公司名        }    }    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);    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.