Qt Creator:QSqlTableModel的进阶

来源:互联网 发布:windows画图软件 编辑:程序博客网 时间:2024/06/01 14:34

进阶的文件:MyWIdget2.h和MyWidget.cpp

工作:
只要是把数据库中的数据的导到窗口中,然后在窗口中对数据的更改,删除,添加。(其中对代理的处理和显示的数据的要求的处理)

建立的文件:
这里写图片描述

MyWidget2.h

#ifndef MYWIDGET2_H#define MYWIDGET2_H#include <QObject>#include <QSqlTableModel>#include <QTableView>#include <QSqlError>#include <QSqlDatabase>#include <QSqlRecord>#include <QVBoxLayout>#include <QHBoxLayout>#include <QPushButton>#include <QMessageBox>//代理#include <QItemDelegate>#include <QComboBox>//将性别那列的格子改成复选框class TAcount : public QItemDelegate{public:    QWidget *createEditor(QWidget *parent,                          const QStyleOptionViewItem &option,                          const QModelIndex &index) const    {        if(index.column() == 0)            return NULL;        if(index.column() ==3)        {            QComboBox *combox = new QComboBox(parent);            combox->addItem("男");            combox->addItem("女");            return combox;        }        return QItemDelegate::createEditor(parent,option,index);    }};#if 0class GenderDelegate : public QItemDelegate{public:    QWidget *createEditor(QWidget *parent,                          const QStyleOptionViewItem &,                          const QModelIndex &) const    {        QComboBox *combox = new QComboBox(parent);        combox->addItem("男");        combox->addItem("女");        return combox;    }};class ReadOnlyDelegate : public QItemDelegate{public:    QWidget *createEditor(QWidget *,                          const QStyleOptionViewItem &,                          const QModelIndex &) const    {        return NULL;    }};#endif//如果性别出现数据是0,将数据变成女,1,就变成男class MyTableModel : public QSqlTableModel{public:    QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const    {        if(idx.column() != 3)            return QSqlTableModel::data(idx,role);        QVariant var = QSqlTableModel::data(idx,role);//获得数据所在的行和列        if(var == 0)        {            return "女";        }        return "男";    }    bool setData(const QModelIndex &index,                const QVariant &value, int role)    {        if(index.column()!=3)          return QSqlTableModel::setData(index,value,role);        if(value == "男")            return QSqlTableModel::setData(index,1,role);        return QSqlTableModel::setData(index,0,role);    }};class MyWidget2 : public QWidget{    Q_OBJECTpublic:    explicit MyWidget2(QWidget *parent = 0);    QSqlTableModel *_model;    QTableView *_view;signals:public slots:    void slotSubmitClicked();//更改    void slotDeleteClicked();//删除    void slotAddClicked();//添加};#endif // MYWIDGET2_H

MyWidget2.cpp

#include "MyWidget2.h"//在显示的窗口中修改数据,删除,关闭窗口后会自动提交到数据库中MyWidget2::MyWidget2(QWidget *parent) :    QWidget(parent){  _model = new QSqlTableModel;  _model->setTable("account");  _model->select();  _model->setEditStrategy(QSqlTableModel::OnManualSubmit);//编辑策略(现在这个是修改窗口中数据,不会向数据库更新)  _model->setHeaderData(0,Qt::Horizontal,"编号");//改动表的列名(水平的,只是在model修改 显示,数据库中没有改)  _model->setHeaderData(1,Qt::Horizontal,"账号");  _model->setHeaderData(2,Qt::Horizontal,"密码");  _model->setHeaderData(3,Qt::Horizontal,"性别");  _view = new QTableView;  _view->setModel(_model);  // _view->hideColumn(1);//隐藏第二列  //_view->setItemDelegateForColumn(3,new GenderDelegate);//代理(对列)  //_view->setItemDelegateForColumn(0,new ReadOnlyDelegate);//代理只能读不能修改第一列    _view->setItemDelegate(new TAcount);//对整个表代理(可以代替GenderDelegate和ReadOnlyDelegate类)  QVBoxLayout *layout = new QVBoxLayout(this);  layout->addWidget(_view);  QHBoxLayout *hBox = new QHBoxLayout;  layout->addLayout(hBox);  hBox->addStretch();//加个弹簧,把按钮弄到右边  QPushButton *del = new QPushButton("删除");  connect(del,SIGNAL(clicked()),this,SLOT(slotDeleteClicked()));  hBox->addWidget(del);  QPushButton *submit = new QPushButton("提交");  connect(submit,SIGNAL(clicked()),this,SLOT(slotSubmitClicked()));  hBox->addWidget(submit);  QPushButton *add = new QPushButton("添加");  connect(add,SIGNAL(clicked()),this,SLOT(slotAddClicked()));  hBox->addWidget(add);}void MyWidget2::slotDeleteClicked(){  //通过_view去获取被选中的部分的数据model  QItemSelectionModel *selectModel = _view->selectionModel();  //通过选中的数据结构,获取这些格子的model Index,用来知道这些格子在model数据结构中的位置  QModelIndexList selectList = selectModel->selectedIndexes();  QList<int> delRow;  //遍历这些格子,获取格子所在的行,因为可能存在相同的行,所以去重  for(int i = 0;i < selectList.size(); ++i)  {      QModelIndex index = selectList.at(i);      // _model->removeRow(index.row());      delRow << index.row();//将遍历的结果放在QList中  }  while(delRow.size() > 0)  {      int row = delRow.at(0);      delRow.removeAll(row);      _model->removeRow(row);  }  _model->submitAll();}void MyWidget2::slotAddClicked()//添加结束之后还要点击一下提交{    //_model->database().transaction();//事务的开始    //事务要做的就是添加三行数据,要么全添加上 要么 就一个也不添加    QSqlRecord record = _model->record();    _model->insertRecord(-1,record);}void MyWidget2::slotSubmitClicked(){    if(!_model->submitAll())    {        QMessageBox::critical(this,"ERROR",QSqlDatabase::database().lastError().text());      // _model->database().rollback();//没成功就恢复到添加之前    }  // else//      _model->database().commit();//将整个数据库进行提交}

main.cpp

#include <QApplication>#include "MyWidget2.h"#include <QDebug>#include <QSqlError>int main(int argc,char **argv){    QApplication app(argc,argv);    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");    db.setHostName("127.0.0.1");    db.setUserName("root");    db.setPassword("123456");    db.setDatabaseName("food");//要链接的数据库名    bool bRet = db.open();    if(bRet == false)    {        qDebug() << "error open database" << db.lastError().text();        exit(0);    }    qDebug() << "open database success";    MyWidget2 w;    w.show();    return app.exec();}

有什么问题请联系我:839505138.