QT连接数据库:QML中实现操作(QSqlTableModel)

目录

一.pro文件添加模块

二.添加头文件

三.连接数据库

四.继承QSqlTableModel

五.重写 data() 和 roleNames() 两个函数

六.设置表名

七.插入功能

八.删除功能

九.修改功能 

十.更新功能

十一.注册

十二.效果演示

1.数据库

2.操作界面

3.编辑功能

十三.代码演示

.sqlconnect.h

sqlconnect.cpp

userinfomodeltest.h

userinfomodeltest.cpp

main.cpp

Test.qml

EditUserInfo.qml

CreatUserInfo.qml

一.pro文件添加模块

1.SQL模块

2.qml模块

二.添加头文件

包含#include <QSqlDatabase>时,QSqlDatabase类提供了一个连接到数据库的接口,您可以使用它来执行SQL查询和管理数据库连接。

#include <QSqlQuery>时,可以在Qt应用程序中使用QSqlQuery类来执行SQL查询。QSqlQuery类提供了一个接口,用于执行SQL语句,如SELECT、INSERT、UPDATE、DELETE等,并处理查询结果。

#include <QSqlTableModel>时,可以在Qt应用程序中使用QSqlTableModel类来操作数据库表。QSqlTableModel是一个高级的SQL表模型,它提供了一个方便的接口来读取和写入单个数据库表的数据,而无需编写SQL语句。

#include <QSqlRecord>时,可以在Qt应用程序中使用QSqlRecord类来表示数据库表中的一条记录(行)。QSqlRecord提供了一种方便的方式来访问和操作记录中的字段(列)数据。

#include <QAbstractListModel> 是在Qt中使用模型(Model)类库时,引入抽象基类   QAbstractListModel 的声明。QAbstractListModel 是所有 Qt 模型的基类,它定义了模型的基本接口,用于数据的存储和提供给视图(View)进行渲染。

三.连接数据库

1.qDebug() << QSqlDatabase::drivers(); 打印出 Qt 支持的所有数据库驱动列表。

2.QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); 创建一个 SQLite 数据库连接,并将其添加到 QSqlDatabase 对象中。

3.db.setDatabaseName("E:/cesi.db"); 设置数据库文件的路径。在这个例子中,数据库文件是 E:/cesi.db

4.if(!db.open()){...} 尝试打开数据库连接。如果打开失败,它会打印出错误信息,包括 db.lastError().text() 返回的错误描述。

四.继承QSqlTableModel

1.QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;

这个函数用于返回与给定模型索引 index 关联的数据项的值。role 参数指定了数据的用途,例如,它可以是 Qt::DisplayRole 用于显示文本,Qt::DecorationRole 用于显示图标,Qt::EditRole 用于编辑等。QVariant 是 Qt 中用于封装各种数据类型的通用类型。

2.QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;

这个函数用于返回模型中使用的角色名称。在某些情况下,例如在使用 QML 时,视图需要知道每个角色的名称,以便正确地显示数据。roleNames 函数返回一个 QHash,其中键是角色的整数值,值是对应的角色名称(以 QByteArray 形式)。

五.重写 data() 和 roleNames() 两个函数

在 Qt 中自定义一个模型类 UserInfoModelTest,该类继承自 QSqlTableModel,并重写 data() 和 roleNames() 两个函数。这个自定义模型用于提供数据库中的用户信息数据给视图组件。

data() 函数的作用是根据给定的 QModelIndex 和 role 返回相应的数据。在这个函数中,如果 role 小于 Qt::UserRole,则直接调用基类的 data() 函数来获取数据。如果 role 大于等于 Qt::UserRole,则根据 role 的值从数据库记录中获取相应的数据。

roleNames() 函数的作用是定义自定义角色名称。在 Qt 中,Qt::UserRole 是一个特殊的角色,通常用于自定义角色。在这个函数中,为从 Qt::UserRole 开始的每个自定义角色定义了一个名称,这些名称将用于在视图中显示数据。

六.设置表名

七.插入功能

1.h

2.cpp

3.qml

八.删除功能

1.h

2.cpp

3.qml

九.修改功能 

1.h

2.cpp

3.qml

十.更新功能

十一.注册

十二.效果演示

1.数据库

2.操作界面

3.编辑功能

十三.代码演示

.sqlconnect.h

#ifndef SQLCONNECT_H
#define SQLCONNECT_H

#include <QObject>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlTableModel>
#include <QSqlRecord>
#include <QAbstractListModel>



class SQLconnect : public QObject
{
    Q_OBJECT
public:
    explicit SQLconnect(QObject *parent = 0);

signals:

public slots:

  private:
    QSqlTableModel *model;
};




#endif




sqlconnect.cpp

连接数据库

#include "sqlconnect.h"

SQLconnect::SQLconnect(QObject *parent) : QObject(parent)
{
     //打印Qt支持的数据库驱动
     qDebug() << QSqlDatabase::drivers();

     QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

     db.setDatabaseName("E:/cesi.db");


     if(!db.open()){
         qDebug()<<"連接失敗"<<"connnect to error"<<db.lastError().text();
     }else{
         qDebug()<<"連接成功";
     }
}


userinfomodeltest.h

#ifndef USERINFOMODELTEST_H
#define USERINFOMODELTEST_H

#include <QObject>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlTableModel>
#include <QSqlRecord>
#include <QAbstractListModel>

class UserInfoModelTest : public QSqlTableModel
{
    Q_OBJECT

public:
    UserInfoModelTest(QObject *parent = nullptr);
    QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
    QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;

    Q_INVOKABLE void insertRow(int row, const int &dataID, const QString &name, const QString &Bir,
                               const QString &sex,const QString &phone,
                               const QString &footlength, const QString &creation,const QString &weight,
                               const QString &shoesize,const QString &address);

    Q_INVOKABLE void modifyRowData(int row, const int &dataID, const QString &name, const QString &Bir,
                             const QString &sex, const QString &phone, const QString &footlength,
                             const QString &creation, const QString &weight, const QString &shoesize,
                             const QString &address);

    Q_INVOKABLE void deleteRow(int row);

    Q_INVOKABLE bool updata();


signals:


public slots:


};
#endif // USERINFOMODELTEST_H

userinfomodeltest.cpp

功能操作

#include "userinfomodeltest.h"

#include <QQmlEngine>
#include <QDateTime>
#include <QSqlRecord>
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QDir>

UserInfoModelTest::UserInfoModelTest(QObject *parent): QSqlTableModel(parent)
{
    setTable("userInfoTab");
    setEditStrategy(QSqlTableModel::OnManualSubmit);
    select();
}

QVariant UserInfoModelTest::data(const QModelIndex &index, int role) const
{
    if (role < Qt::UserRole)
        return QSqlTableModel::data(index, role);

    const QSqlRecord sqlRecord = record(index.row());
    //qDebug() << sqlRecord.value(role - Qt::UserRole);

    switch (role) {
    case Qt::UserRole:
        sqlRecord.value(0).toInt();
        break;
    case Qt::UserRole+1:
        sqlRecord.value(1).toString();
        break;
    case Qt::UserRole+2:
        sqlRecord.value(2).toString();
        break;
    case Qt::UserRole+3:
        sqlRecord.value(3).toString();
        break;
    case Qt::UserRole+4:
        sqlRecord.value(4).toString();
        break;
    case Qt::UserRole+5:
        sqlRecord.value(5).toString();
        break;
    }
    return sqlRecord.value(role - Qt::UserRole);
}

QHash<int, QByteArray> UserInfoModelTest::roleNames() const
{
    QHash<int, QByteArray> names;
    names[Qt::UserRole] = "dataID";
    names[Qt::UserRole + 1] = "name";
    names[Qt::UserRole + 2] = "Bir";
    names[Qt::UserRole + 3] = "sex";
    names[Qt::UserRole + 4] = "creation";
    names[Qt::UserRole + 5] = "finally";
    return names;
}

void UserInfoModelTest::insertRow(int row, const int &dataID, const QString &name, const QString &Bir,
                                  const QString &sex,const QString &phone,const QString &footlength,
                                  const QString &creation,const QString &weight,const QString &shoesize,
                                  const QString &address )
{
    QSqlRecord record = this->record();
    record.setValue("dataID", dataID);
    record.setValue("name", name);
    record.setValue("Bir", Bir);
    record.setValue("sex", sex);
    record.setValue("phone", phone);
    record.setValue("footlength", footlength);
    record.setValue("creation", creation);
    record.setValue("weight", weight);
    record.setValue("shoesize", shoesize);
    record.setValue("address", address);
    //record.setValue("finally", finally);

    if (!insertRecord(row, record)) {
        qWarning() << "Failed to insert row:" << lastError().text();
    }
    submitAll();
    select();

}



void UserInfoModelTest::modifyRowData(int row, const int &dataID, const QString &name, const QString &Bir, const QString &sex,
                                      const QString &phone,const QString &footlength, const QString &creation, const QString &weight,
                                      const QString &shoesize, const QString &address)
{

        QString sql = QString("UPDATE %1 SET name = :name, Bir = :Bir, sex = :sex, creation = :creation,phone = :photo, "
                              "footlength = :footlength,weight = :weight,shoesize=:shoesize,"
                              "address = :address WHERE dataID = :dataID").arg("userInfoTab");
        QSqlQuery query;

        query.prepare(sql);
        query.bindValue(":name",name);
        query.bindValue(":Bir",Bir);
        query.bindValue(":sex",sex);
        query.bindValue(":creation",creation);
        query.bindValue(":photo",phone);
        query.bindValue(":footlength",footlength);
        query.bindValue(":weight",weight);
        query.bindValue(":shoesize",shoesize);
        query.bindValue(":address",address);
        query.bindValue(":dataID",dataID);
        query.exec();
        select();


        qWarning() << "Invalid row index:" << row;

}


void UserInfoModelTest::deleteRow(int row)
{
    if (row >= 0 && row < this->rowCount()) {
        removeRow(row);
        submitAll();
    } else {
        qWarning() << "Invalid row index:" << row;
    }
}

bool UserInfoModelTest::updata()
{
    qDebug()<<"SSSSSSSSSS";
    select();
   return true;
}

main.cpp

注册页面

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "sqlconnect.h"
#include "userinfomodeltest.h"
#include <QQmlContext>
#include <QQmlEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    SQLconnect ss;

    qmlRegisterType<UserInfoModelTest>("QMLUserInfoModelTest", 1, 0, "QMLUserInfoModelTest");


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

    return app.exec();
}

Test.qml

主界面

import QtQuick 2.7
import QMLUserInfoModelTest 1.0
import QtQuick.Controls 1.4

Rectangle {
    visible: true
    width: 800
    height: 600

    QMLUserInfoModelTest{
        id:_aaaaaaaaaa
    }

    CreatUserInfo{
        id: creatUserInfo
        anchors.centerIn: parent
    }

    EditUserInfo{
        id: _editUserInfo
    }


    Button{
        id:_creatUserInfoButton
        text: "新建"
        onClicked: {
            creatUserInfo.visible = true
        }
    }

    Button{
        anchors.left: _creatUserInfoButton.right
        anchors.leftMargin: 30
        text:"刪除"
        onClicked: {
             _aaaaaaaaaa.deleteRow(userHistoryTableTest.currentRow)
        }
    }

    Button{
        anchors.left: _creatUserInfoButton.right
        anchors.leftMargin: 110
        text:"编辑"
        onClicked: {
            if(userHistoryTableTest.currentRow >= 0)
            {

            _editUserInfo._number = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,0))
            _editUserInfo._name = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,1))
            _editUserInfo._bir = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,2))
            _editUserInfo._sex = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,3))
            _editUserInfo._creatDate = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,4))
            _editUserInfo._tel = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,6))
            _editUserInfo._footlength = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,7))
            _editUserInfo._weight = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,8))
            _editUserInfo._shoesize = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,9))
            _editUserInfo._address = _aaaaaaaaaa.data(_aaaaaaaaaa.index(userHistoryTableTest.currentRow,10))

            _editUserInfo.visible = true
            }
        }
    }


    TableView {
        id: userHistoryTableTest
        width: 640
        height: 480
        anchors.left: parent.left
        anchors.top: _creatUserInfoButton.bottom
        anchors.topMargin: 30
        TableViewColumn { role: "dataID"; title: "编号"; width: 50 }
        TableViewColumn { role: "name"; title: "姓名"; width: 100 }
        TableViewColumn { role: "Bir"; title: "生日"; width: 100 }
        TableViewColumn { role: "sex"; title: "性别"; width: 100 }
        TableViewColumn { role: "creation"; title: "建立日期"; width: 100 }
        TableViewColumn { role: "finally"; title: "最后测量日"; width: 100 }

        model: _aaaaaaaaaa

        headerDelegate: Rectangle {
            width:  10
            height:  30
            border.width: 1
            border.color: "#838B8B"
            color: "#4F4F4F"
            Text {
                anchors.centerIn: parent
                text: styleData.value
                color: "white"
            }
        }

        onCurrentRowChanged: {
            console.log("sssssssssssssssssssss")
            console.log("当前选中的行是:" + currentRow)
        }
    }
}

EditUserInfo.qml

编辑数据界面

import QtQuick 2.0
import QtQuick.Controls 1.4
import QMLUserInfoModelTest 1.0

Rectangle {
    id:_root
    z: userHistoryTableTest.z + 1
    anchors.centerIn: parent
    color:  "#A0A0A0"
    width: 600
    height: 500
    visible: false
    border.color: "black"
    border.width: 1

    property var _number:""
    property var _creatDate:""
    property var _name:""
    property var _bir:""
    property var _sex:""
    property var _tel:""
    property var _footlength: ""
    property var _weight: ""
    property var _shoesize: ""
    property var _address: ""


    Rectangle {
        id:_EditingLabel
        width: parent.width
        height: 40
        color: "black"
        Text {
            anchors.left: parent.left
            anchors.leftMargin: 15
            anchors.verticalCenter: parent.verticalCenter
            text: qsTr("编辑客户")
            font.pixelSize: 20
            color: "white"
        }
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 30
        text: qsTr("编号")
        font.pixelSize: 20
    }

    TextField{
        id:_dataidEditing
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 25
        text: _number
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 290
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 30
        text: qsTr("建立日期")
        font.pixelSize: 20
    }

    TextField{
        id:_creationEditing
        anchors.left: parent.left
        anchors.leftMargin: 390
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 25
        width: 180
        height: 30
        text: _creatDate
        font.pixelSize: 20
    }


    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 90
        text: qsTr("姓名")
        font.pixelSize: 20
    }

    TextField{
        id:_nameEditing
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 85
        text:_name
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 290
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 90
        text: qsTr("生日")
        font.pixelSize: 20
    }

    TextField{
        id:_birEditing
        anchors.left: parent.left
        anchors.leftMargin: 390
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 85
        text: _bir
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Image {
        anchors.right:   _birEditing.right
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 87
        width: 26
        height: 26
       // source: "qrc:/Image/resources/date.png"
        MouseArea{
            anchors.fill:parent
            onClicked: {
               calendar4.visible = true
            }
        }
    }

    Calendar {
        id: calendar4
        anchors.bottom:_birEditing.top
        anchors.left: _birEditing.left
        z:_root.z + 1
        visible: false
        weekNumbersVisible: true
        onClicked: {
            selectedDate = date
            visible = false
            _birEditing.text = new Date(calendar4.selectedDate).toLocaleDateString("yy-MM-dd")
        }
    }


    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 150
        text: qsTr("性别")
        font.pixelSize: 20
    }


    ComboBox{
        id:_sexEditing
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 145
        width: 180
        height: 30
        model: [ "男", "女"]
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 290
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 150
        text: qsTr("电话")
        font.pixelSize: 20
    }

    TextField{
        id:_phoneEditing
        anchors.left: parent.left
        anchors.leftMargin: 390
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 145
        text:_tel
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 210
        text: qsTr("足长")
        font.pixelSize: 20
    }

    SpinBox{
        id:_footlengthEditing
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 205
        width: 180
        height: 30
        //text: _footlength
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 290
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 210
        text: qsTr("体重")
        font.pixelSize: 20
    }

    SpinBox{
        id:_weightEditing
        anchors.left: parent.left
        anchors.leftMargin: 390
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 205
        width: 180
        height: 30
        //text: _weight
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 270
        text: qsTr("鞋码")
        font.pixelSize: 20
    }

    SpinBox{
        id:_shoesizeEditing
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 265
        width: 180
        height: 30
        //text: _shoesize
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 330
        text: qsTr("地址")
        font.pixelSize: 20
    }

    TextField{
        id:_addressEditing
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_EditingLabel.bottom
        anchors.topMargin: 325
        width: 500
        height: 30
        text: _address
        font.pixelSize: 20
    }

    Button{
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.rightMargin: 120
        anchors.bottomMargin: 30
        width: 60
        height: 40
        Text {
            anchors.centerIn: parent
            text: qsTr("储存")
            font.pixelSize: 20
        }

        onClicked: {
            var dataId = _dataidEditing.text
            var Bir = _birEditing.text
            var name = _nameEditing.text
            var sex = _sexEditing.model[_sexEditing.currentIndex]
            var phone = _phoneEditing.text
            var footlength = _footlengthEditing.value
            var weight = _weightEditing.value
            var shoesize = _shoesizeEditing.value
            var address = _addressEditing.text
            var creation = _creationEditing.text
            console.log("aaaaaaaaaaaaaaaaaaaaaaaa"+dataId+name+Bir+sex+phone+footlength+creation+weight+shoesize+address)
            _aaaaaaaaaa.modifyRowData(userHistoryTableTest.currentRow, dataId,
                  name, Bir ,sex, phone , footlength ,creation,weight, shoesize, address)
           _aaaaaaaaaa.updata()
            _root.visible = false
        }

    }

    Button{
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.rightMargin: 30
        anchors.bottomMargin: 30
        width: 60
        height: 40
        Text {
            anchors.centerIn: parent
            text: qsTr("放弃")
            font.pixelSize: 20
        }
        onClicked: {
            _root.visible = false
        }
    }
}

.

CreatUserInfo.qml

创建新数据界面

import QtQuick 2.0
import QtQuick.Controls 1.4
import QMLUserInfoModelTest 1.0

Rectangle {
    id:_root
    z: userHistoryTableTest.z + 1
    anchors.centerIn: parent
    color:  "#A0A0A0"
    width: 600
    height: 500
    visible: false
    border.color: "black"
    border.width: 1

    Rectangle {
        id:_addnewLabel
        width: parent.width
        height: 40
        color: "black"
        Text {
            anchors.left: parent.left
            anchors.leftMargin: 15
            anchors.verticalCenter: parent.verticalCenter
            text: qsTr("新增使用者")
            font.pixelSize: 20
            color: "white"
        }
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 30
        text: qsTr("编号")
        font.pixelSize: 20
    }

    TextField{
        id:_dataidTextField
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 25
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 290
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 30
        text: qsTr("建立日期")
        font.pixelSize: 20
    }

    TextField{
        id:_creationTextField
        anchors.left: parent.left
        anchors.leftMargin: 390
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 25
        width: 180
        height: 30
        font.pixelSize: 20
    }


    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 90
        text: qsTr("姓名")
        font.pixelSize: 20
    }

    TextField{
        id:_nameTextField
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 85
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 290
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 90
        text: qsTr("生日")
        font.pixelSize: 20
    }

    TextField{
        id:_birTextField
        anchors.left: parent.left
        anchors.leftMargin: 390
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 85
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Image {
        anchors.right:   _birTextField.right
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 87
        width: 26
        height: 26
        MouseArea{
            anchors.fill:parent
            onClicked: {
                calendar3.visible = true
            }
        }
    }

    Calendar {
        id: calendar3
        anchors.bottom:_birTextField.top
        anchors.left: _birTextField.left
        z:_root.z + 1
        visible: false
        weekNumbersVisible: true
        onClicked: {
            selectedDate = date
            visible = false
            _birTextField.text = new Date(calendar3.selectedDate).toLocaleDateString("yy-MM-dd")
        }
    }


    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 150
        text: qsTr("性别")
        font.pixelSize: 20
    }

    ComboBox{
        id:_sexTextField
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 145
        width: 180
        height: 30
        model: [ "男", "女"]
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 290
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 150
        text: qsTr("电话")
        font.pixelSize: 20
    }

    TextField{
        id:_phoneTextField
        anchors.left: parent.left
        anchors.leftMargin: 390
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 145
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 210
        text: qsTr("足长")
        font.pixelSize: 20
    }

    SpinBox{
        id:_footlengthTextField
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 205
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 290
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 210
        text: qsTr("体重")
        font.pixelSize: 20
    }

    SpinBox{
        id:_weightTextField
        anchors.left: parent.left
        anchors.leftMargin: 390
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 205
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 270
        text: qsTr("鞋码")
        font.pixelSize: 20
    }

    SpinBox{
        id:_shoesizeTextField
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 265
        width: 180
        height: 30
        font.pixelSize: 20
    }

    Label{
        anchors.left: parent.left
        anchors.leftMargin: 20
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 330
        text: qsTr("地址")
        font.pixelSize: 20
    }

    TextField{
        id:_addressTextField
        anchors.left: parent.left
        anchors.leftMargin: 70
        anchors.top:_addnewLabel.bottom
        anchors.topMargin: 325
        width: 500
        height: 30
        font.pixelSize: 20
    }

    Button{
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.rightMargin: 120
        anchors.bottomMargin: 30
        width: 60
        height: 40
        Text {
            anchors.centerIn: parent
            text: qsTr("储存")
            font.pixelSize: 20
        }
        onClicked: {
            var dataId = _dataidTextField.text
            var Bir = _birTextField.text
            var name = _nameTextField.text
            var sex = _sexTextField.model[_sexTextField.currentIndex]
            var phone = _phoneTextField.text
            var footlength = _footlengthTextField.value
            var weight = _weightTextField.value
            var shoesize = _shoesizeTextField.value
            var address = _addressTextField.text
            var creation = _creationTextField.text

            _aaaaaaaaaa.insertRow(_aaaaaaaaaa.rowCount, dataId, name, Bir ,sex,
                                       phone , footlength ,
                                       creation , weight, shoesize, address)

            _root.visible = false

        }
    }

    Button{
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.rightMargin: 30
        anchors.bottomMargin: 30
        width: 60
        height: 40
        Text {
            anchors.centerIn: parent
            text: qsTr("放弃")
            font.pixelSize: 20
        }
        onClicked: {
            _root.visible = false
        }
    }


}

  • 31
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Qt 6连接数据库可以使用QtSql模块和QMLQtQuick.Controls 2.5模块SqlTableModel。以下是一个简单的示例,展示如何在QML使用SqlTableModel连接到SQLite数据库: 1. 在Qt Creator,创建一个新的Qt Quick应用程序项目。 2. 在项目文件夹添加一个SQLite数据库文件,例如“test.db”。 3. 在项目文件夹创建一个新的QML文件,例如“Database.qml”。 4. 在“Database.qml”文件添加以下内容: ``` import QtQuick.Controls 2.5 import QtQuick.Controls.Material 2.5 import QtSql 1.0 ApplicationWindow { id: window width: 640 height: 480 visible: true title: "SQLite Database" SqlTableModel { id: model tableName: "test" database: QSqlDatabase.addDatabase("QSQLITE") source: "test.db" selectStatement: "SELECT * FROM test" onDatabaseChanged: { if (database.open()) { console.log("Database opened successfully") } else { console.log("Error opening database: " + database.lastError().text()) } } } TableView { id: tableView width: parent.width height: parent.height - 50 model: model delegate: Rectangle { width: tableView.columnWidthProvider(index) height: tableView.rowHeightProvider(index) Text { text: styleData.value font.pixelSize: 16 wrapMode: Text.WordWrap anchors.fill: parent anchors.margins: 10 } } } Button { text: "Add Row" anchors.bottom: parent.bottom onClicked: { model.insertRow(model.rowCount) } } } ``` 5. 运行应用程序并查看结果。 此示例创建了一个名为“test”的表,并在其添加了一些数据。然后,使用SqlTableModelQML连接到SQLite数据库,将表格数据显示在一个TableView,并提供了一个按钮来添加新行。在实际应用程序,您需要根据您的特定情况进行适当的更改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值