Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. When I am clicking on Show Table Button Then Records are not showing on Table (TableData.qml) file. Please suggest where is error

When I am clicking on Show Table Button Then Records are not showing on Table (TableData.qml) file. Please suggest where is error

Scheduled Pinned Locked Moved Unsolved General and Desktop
2 Posts 2 Posters 165 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    Pappu Kumar Keshari
    wrote on last edited by
    #1

    These are my whole codes

    dbmanager.h==>

    #ifndef DBMANAGER_H
    #define DBMANAGER_H
    #include <QObject>
    #include <QSqlDatabase>
    class DbManager : public QObject
    {
    Q_OBJECT
    public:
    explicit DbManager(QObject *parent = nullptr);

    DbManager(const QString& path);
    
    ~DbManager();
    
    bool isOpen() const;
    
    bool createTable();
    
    bool addRecord(const QString &name, const QString &fatherName,const QString &motherName);
    
    void printAllRecords() const;
    
    QList<QVariantMap> execQuery(const QString& query);
    

    public slots:

    Q_INVOKABLE bool saveToSqlite(const QString &data);
    
    Q_INVOKABLE bool showTable();
    

    private:
    QSqlDatabase m_db;
    };

    #endif // DBMANAGER_H

    dbmanager.cpp==>

    #include "dbmanager.h"
    #include <QFile>
    #include <QTextStream>
    #include <QDateTime>
    #include <QDebug>
    #include <QSqlQuery>
    #include <QSqlError>
    #include <QSqlRecord>

    DbManager::DbManager(QObject *parent) : QObject(parent){}

    DbManager::DbManager(const QString &path)
    {
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(path);

    if (!m_db.open())
    {
        qDebug() << "Error: connection with database fail";
    }
    else
    {
        qDebug() << "Database Connected Successfully !!!";
    }
    createTable();
    

    }

    DbManager::~DbManager()
    {
    if (m_db.isOpen())
    {
    m_db.close();
    }
    }

    bool DbManager::isOpen() const
    {
    return m_db.isOpen();
    }

    bool DbManager::createTable()
    {
    bool success = false;

    QSqlQuery query;
    
    query.prepare("CREATE TABLE  student (id INTEGER PRIMARY KEY, name TEXT, fatherName TEXT, motherName TEXT)");
    if (!query.exec())
    {
        qDebug() << "Couldn't create the table 'student': one might already exist.";
        success = false;
    }
    
    return success;
    

    }

    bool DbManager::addRecord(const QString &name, const QString &fatherName, const QString &motherName)
    {
    if (isOpen())
    {
    QSqlQuery queryAdd;
    queryAdd.prepare("INSERT INTO student (name, fatherName, motherName) "
    "VALUES (:name, :fatherName, :motherName)");
    queryAdd.bindValue(":name", name);
    queryAdd.bindValue(":fatherName", fatherName);
    queryAdd.bindValue(":motherName", motherName);

        if (queryAdd.exec())
        {
            return true;
        }
        else
        {
            qDebug() << "Data insertion failed: " << queryAdd.lastError();
        }
    }
    else
    {
        qDebug() << "Database is not open!";
    }
    
    return false;
    

    }

    void DbManager::printAllRecords() const
    {
    qDebug() << "Persons in Database:";
    QSqlQuery query("SELECT * FROM student");

    if (!query.exec())
    {
        qDebug() << "Error executing query: " << query.lastError().text();
        return;
    }
    
    while (query.next())
    {
        QString name = query.value("name").toString();
        QString fatherName = query.value("fatherName").toString();
        QString motherName = query.value("motherName").toString();
    
        qDebug() << "Name: " << name;
        qDebug() << "Father's Name: " << fatherName;
        qDebug() << "Mother's Name: " << motherName;
    }
    

    }

    bool DbManager::saveToSqlite(const QString &data)
    {
    QStringList list =data.split(",");
    qDebug()<<"Input Data" <<list;

    addRecord(list.at(0),list.at(1),list.at(2));
    
    printAllRecords();
    

    }

    QList<QVariantMap> DbManager::execQuery(const QString& query)
    {
    QList<QVariantMap> results;

    if (isOpen())
    {
        QSqlQuery sqlQuery(query);
    
        if (sqlQuery.exec())
        {
            while (sqlQuery.next())
            {
                QVariantMap row;
                row["name"] = sqlQuery.value("name").toString();
                row["fatherName"] = sqlQuery.value("fatherName").toString();
                row["motherName"] = sqlQuery.value("motherName").toString();
                results.append(row);
            }
        }
        else
        {
            qDebug() << "Query execution failed: " << sqlQuery.lastError();
        }
    }
    else
    {
        qDebug() << "Database is not open!";
    }
    
    return results;
    

    }

    main.cpp==>

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlContext>
    #include <dbmanager.h>

    static const QString path = "example1.db";

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

    DbManager dbManager(path); 
    
    engine.rootContext()->setContextProperty("d_bmanager", &dbManager);
    
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
    if (engine.rootObjects().isEmpty())
        return -1;
    
    return app.exec();
    

    }

    main.qml==>

    import QtQuick 2.15
    import QtQuick.Window 2.15
    import QtQuick.Controls 2.12
    import QtQuick.Layouts 1.3
    import QtQuick.Dialogs 1.2

    Window {
    id: window
    width: 700
    height: 1050
    visible: true
    title: qsTr("Student Login Form")
    flags: Qt.SplashScreen | Qt.FramelessWindowHint

    property string name: ""
    property string fatherName: ""
    property string motherName: ""
    
    //Top Heading
    Rectangle{
        id:containerRect
        y: 0
        height: 50
        anchors.left:  parent.left
        anchors.right: parent.right
        anchors.leftMargin: 0
        anchors.rightMargin: 0
        color: "dodgerblue"
        border.color: "#000000"
        border.width: 6
    
        //Heading objectName
        Text{
            width: 245
            height: 29
            anchors.centerIn: parent
            text: "Student Login Form"
            font.family: "Times New Roman"
            anchors.verticalCenterOffset: -3
            anchors.horizontalCenterOffset: 3
            color: "#fefff6"
            font.pointSize: 20
        }
    
        Button {
            id: closeButton
            x: 580
            y: 10
            width: 100
            height: 30
            text: qsTr("Close")
            font.bold: true
            MouseArea{
                anchors.fill: parent
                onClicked: {
                    Qt.quit();
                }
    
                Rectangle{
                    anchors.centerIn:parent
                    width: 98
                    height: 26
                    radius: 2
                    color: "red"
                }
            }
        }
    }
    
    Rectangle{
    
        id:containerRect1
        color: "#f1ffffff"
        radius: 6
        border.color: "#f797187f"
        border.width: 2
        anchors.fill: parent
        anchors.rightMargin: 8
        anchors.bottomMargin: 29
        anchors.leftMargin: 9
        anchors.topMargin: 60
    
        GroupBox {
            id: groupBox
            height: 400
            width: 500
            font.pointSize: 11
            //anchors.centerIn:parent
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.top: parent.top
            anchors.bottomMargin: -1
            layer.textureSize.width: 10
            anchors.rightMargin: 15
            anchors.leftMargin: 11
            anchors.topMargin: 5
            title: qsTr("Personal Details")
            spacing: 10
    
            Label  {
                id: label
                x: 50
                y: 25
                text: qsTr("Name")
            }
    
            Label {
                id: label1
                x: 50
                y: 65
                text: qsTr("Father's Name")
                rotation: -1.907
            }
    
            Label {
                id: label2
                x: 50
                y: 110
                text: qsTr("Mother's Name")
            }
    
            TextField {
                id: nameTextField
                x: 175
                y: 25
                width: 238
                height: 29
                placeholderText: qsTr("Enter your name")
                onTextChanged: name=text
            }
    
            TextField {
                id: fatherNameTextField
                x: 175
                y: 65
                width: 238
                height: 29
                placeholderText: qsTr("Enter your Father's name ")
                onTextChanged: fatherName=text
            }
    
            TextField {
                id: motherNameTextField
                x: 175
                y: 105
                width: 238
                height: 29
                placeholderText: qsTr("Enter your Mother's name ")
                onTextChanged: motherName=text
            }
        }
    
        Button {
            id: button
            x: 220
            y: 720
            width: 99
            height: 37
            text: qsTr("Submit")
            layer.format: ShaderEffectSource.RGB
            font.weight: font.bold
            font.underline: false
            font.strikeout: false
            font.bold: true
            font.family: "Verdana"
            onClicked: {
                //Save Data From QML to Sqlite
    
                var csv_data =
                        nameTextField.text + "," +
                        fatherNameTextField.text +","+
                        motherNameTextField.text;
                if (d_bmanager.saveToSqlite(csv_data))
                {
                    console.log("Data saved to Sqlite successfully !!!");
                }
                else
                {
                    console.error("Error While Saving Data to Sqlite.");
                }
    
            Rectangle{
                anchors.centerIn: parent
                width: 99
                height: 37
                color: "green"
                anchors.verticalCenterOffset: 2
                anchors.horizontalCenterOffset: 0
            }
        }
    
        StackView{
            id:stackView
            anchors.fill: parent
            initialItem: firstPage
        }
    
        Button {
            id: button2
            x: 350
            y: 720
            width: 99
            height: 37
            text: qsTr("Show Table")
            layer.format: ShaderEffectSource.RGB
            font.weight: font.bold
            font.underline: false
            font.strikeout: false
            font.bold: true
            font.family: "Verdana"
    
            onClicked: {
                d_bmanager.showTable()
                stackView.push(secondPage)
            }
    
            Component{
                id:secondPage
                TableData{}
            }
    
            Rectangle{
                anchors.centerIn: parent
                width: 99
                height: 37
                color: "green"
                anchors.verticalCenterOffset: 2
                anchors.horizontalCenterOffset: 0
            }
        }
    }
    

    }

    TableData.qml==>

    import QtQuick 2.7
    import QtQuick.Window 2.0
    import QtQuick.Controls 1.4

    Window
    {
    width: 700
    height: 500
    visible: true

    Component.onCompleted: {
        // Fetch data from the database here and populate the model
        var query = "SELECT * FROM student";
        var result = d_bmanager.execQuery(query); // Make sure to add this function in DbManager
    
        // Assuming result is an array of objects with properties name, fatherName, motherName
        for (var i = 0; i < result.length; i++) {
            myModel.append({
                               name: result[i].name,
                               fatherName: result[i].fatherName,
                               motherName: result[i].motherName
                           });
        }
    }
    
    TableView {
        id: myTable
        anchors.fill: parent
        anchors.margins: 5
    
        TableViewColumn {
            role: name
            title: "Name"
            width: 250
            horizontalAlignment: Text.AlignHCenter
        }
        TableViewColumn {
            role: fatherName
            title: "Father's Name"
            width: 250
            horizontalAlignment: Text.AlignHCenter
        }
        TableViewColumn {
            role: motherName
            title: "Mother's Name"
            width: 250
            horizontalAlignment: Text.AlignHCenter
        }
        model: myModel
    }
    

    }

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      Please, as already requested several times, stop posting your whole code base and reduce it to the strict minimum required to show your issue.

      And also use coding tags when posting your code. It's the </> button on the text editor tool bar.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      2

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved