【qml】QMl中使用QSqlTableModel

自己工作中用的代码,基本功能可用。

MySqlTableModel.h

#ifndef SQLQUERYMODEL_H
#define SQLQUERYMODEL_H

#include 
#include 
#include 

#include 

class MySqlTableModel : public QSqlTableModel
{
    Q_OBJECT

public:
    explicit MySqlTableModel(QObject *parent = Q_NULLPTR, QSqlDatabase db = QSqlDatabase());
    bool Init();
    virtual QHash roleNames() const;
    QVariant data(const QModelIndex &index, int role) const;
    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);


public slots:
    void insertData(QString insertData);
    void updateData(QString updateData);
    void deleteData(QString deleteData);

private:
    bool parseTblModData(QString &json, QMap &map);
};

#endif // SQLQUERYMODEL_H

MySqlTableModel.cpp

#include "MySqlTableModel.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


MySqlTableModel::MySqlTableModel(QObject *parent, QSqlDatabase db):
    QSqlTableModel(parent, db)
{
    Init();
}

bool MySqlTableModel::Init()
{
    setTable("tbl1");
    setEditStrategy(QSqlTableModel::OnRowChange);
    select();
    setHeaderData(0, Qt::Horizontal, ("col_1"));
    setHeaderData(1, Qt::Horizontal, ("col_2"));
    setHeaderData(2, Qt::Horizontal, ("col_3"));
    setHeaderData(3, Qt::Horizontal, ("col_4"));
    return true;
}

QHash MySqlTableModel::roleNames() const
{
    QHash roleNames;
    for( int i = 0; i < record().count(); i++) {
        roleNames[Qt::UserRole + i + 1] = record().fieldName(i).toUtf8();
    }
    return roleNames;
}

QVariant MySqlTableModel::data(const QModelIndex &index, int role) const
{
    QVariant value = QSqlTableModel::data(index, role);
    if(role < Qt::UserRole)
    {
        value = QSqlTableModel::data(index, role);
    }
    else
    {
        int columnIdx = role - Qt::UserRole - 1;
        QModelIndex modelIndex = this->index(index.row(), columnIdx);
        value = QSqlTableModel::data(modelIndex, Qt::DisplayRole);
    }

    return value;
}

bool MySqlTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    bool ret;
    if(role < Qt::UserRole)
    {
        ret = QSqlTableModel::setData(index, value, role);
    }
    else
    {
        int colIdx = role - Qt::UserRole - 1;
        ret = QSqlTableModel::setData(index, value, Qt::DisplayRole);
    }

    return ret;
}

void MySqlTableModel::insertData(QString data)
{
    QMap map;
    if( !parseTblModData(data, map))
    {
        return;
    }

    QSqlRecord rec = record();
    QMap::iterator ite;
    for(ite = map.begin();  ite != map.end(); ite++)
    {
        rec.setValue(ite.key(), ite.value());

    }
    insertRecord(-1,rec);

    select();


}

void MySqlTableModel::updateData(QString updateData)
{
//    bool ret;
//    ret = removeRow(1, QModelIndex());
//    ret = select();
}

void MySqlTableModel::deleteData(QString deleteData)
{
    bool ret;
    ret = removeRow(rowCount()-1);

    ret = select();

}

main.qml

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1

import QtQuick.Dialogs 1.2

import mylib 1.0

Window {
    visible: true
    width: 1195
    height: 1080
    color: Qt.rgba(20/255, 35/255, 40/255, 0.95)
    //opacity: 0.95

    Row{
        x: 165
        y: 128

        Button{
            id: btnAddRow
            text: "添加"
            onClicked: {
                editLongitude.textInput.forceActiveFocus();
            }
        }
        Button{
            id: btnDelRow
            text: "删除"
            onClicked: {
                model.deleteData(1);
            }
        }
        Button{
            id: btnModRow
            text: "修改"
        }
        Button{
            id: btnSubRow
            text: "提交"
        }
    }

    //
    TableView {
        id: tableView
        x: 180
        y: 188
        width: 700
        height: 500
        //backgroundVisible: false
        selectionMode: SelectionMode.NoSelection

        alternatingRowColors: false

        headerDelegate: Rectangle{
            width: 233
            height: 41
            color: Qt.rgba(46/255,85/255,100/255,0.41);
            border.color: "white"
            border.width: 2
            Text{
                anchors.fill: parent
                anchors.horizontalCenter: parent.horizontalCenter
                anchors.verticalCenter: parent.verticalCenter
                //color: ""
                text: styleData.value
                font.family: "Microsoft YaHei UI"
                font.pixelSize: 22

            }

        }

        TableViewColumn {
            id: colSeqNO
            role: "col_1"
            title: "col_1"
            //width: 100
        }
        TableViewColumn {
            id: colLongitude
            role: "col_2"
            title: "col_2"
            //width: 100
        }
        TableViewColumn {
            id: colLatitude
            role: "col_3"
            title: "col_3"
            //width: 200
        }
        TableViewColumn {
            id: colAltitude
            role: "col_4"
            title: "col_4"
            //width: 100
        }
        model: model
    }

    MySqlTableModel{
        id: model
    }

    // 插入及编辑区
    Row{
        id: grdEdit
        x: 100
        y: 800

        spacing: 50

        COM_TableItem{
            id: editLongitude
            labelText: "col_2"
            inputText: "33"
        }

        COM_TableItem{
            id: editLatitude
            labelText: "col_3"
            inputText: "33"
        }
        COM_TableItem{
            id: editAltitude
            labelText: "col_4"
            inputText: "33"
        }
        Button{
            id: btn
            text: "确认修改"

            onClicked: {
                var insertData = [
                            {
                                "col_2": editLongitude.inputText,
                                "col_3" : editLatitude.inputText,
                                "col_4" : editAltitude.inputText
                            }
                        ];

                var temp = JSON.stringify(insertData);
                model.insertData(temp);
            }
        }
    }
}

main.cpp

#include
#include
#include
#include
#include
#include

#include “MySqlTableModel.h”

int main(int argc, char *argv[])
{
    qmlRegisterType("mylib", 1, 0, "MySqlTableModel");


    //
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    // 创建数据库及表格
    QSqlDatabase   m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("customdb");
    bool ret = m_db.open();
    QSqlQuery query(m_db);

    QString sql;
    sql = QString("drop table tbl1");
    ret = query.exec(sql);

    sql = QString("create table tbl1(col_1 integer PRIMARY KEY autoincrement, \
                                           col_2 NUMERIC(10,5), \
                                           col_3 NUMERIC(10,5), \
                                           col_4 NUMERIC(10,5))");
    ret = query.exec(sql);

    // 插入数据
    if(ret == true)
    {
        for(int i=0; i<10; i++)
        {
            sql = QString("INSERT INTO tbl1 (col_2, col_3, col_4) VALUES (:col_2, :col_3, :col_4)");
            query.prepare(sql);
            query.bindValue(":col_2",   QVariant(i));
            query.bindValue(":col_3",    QVariant(i));
            query.bindValue(":col_4",    QVariant(i));

            ret = query.exec();
            Q_ASSERT(ret != false);
        }
    }


    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

你可能感兴趣的:(【qml】QMl中使用QSqlTableModel)