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. Insert Record in QSqlTableModel with QTableView
Forum Updated to NodeBB v4.3 + New Features

Insert Record in QSqlTableModel with QTableView

Scheduled Pinned Locked Moved Unsolved General and Desktop
3 Posts 2 Posters 5.0k 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.
  • I Offline
    I Offline
    Infinity
    wrote on last edited by
    #1

    I have a QTableModel class like this

    tablemodel.h

    #ifndef TABLEMODEL_H
    #define TABLEMODEL_H
    
    #include <QSqlTableModel>
    #include <QSqlDatabase>
    #include <QSqlRecord>
    #include <QDebug>
    
    class TableModel : public QSqlTableModel
    {
        Q_OBJECT
    
    public:
        explicit TableModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase());
    
    private:
    
    public slots:
        void addRecord();
    };
    
    #endif // TABLEMODEL_H
    
    

    tablemodel.cpp

    #include "tablemodel.h"
    
    TableModel::TableModel(QObject *parent, QSqlDatabase db)
        : QSqlTableModel(parent, db)
    {
        setTable("employee");
        setEditStrategy(QSqlTableModel::OnFieldChange);
        select();
    
        connect(this, SIGNAL (primeInsert()), this, SLOT (on_primeInsert()));
    }
    
    void TableModel::addRecord()
    {
        qDebug() << "addRecord";
        beginInsertRows(QModelIndex(), rowCount(), rowCount());
        QSqlRecord newRecord = record();
        newRecord.setValue("id", 0);
        newRecord.setValue("id", 0);
        newRecord.setValue("name", "Enter Name");
        newRecord.setValue("gender", 0);
        newRecord.setValue("married", 0);
        
        if (insertRow(rowCount())) {
            qDebug() << "New record inserted";
        }
        
        if (insertRecord(rowCount(), newRecord)) {
            qDebug() << "New record inserted";
        }
        
        endInsertRows();
    }
    

    mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    #include <QSql>
    #include <QSqlDatabase>
    #include <QSqlTableModel>
    #include <QSqlRecord>
    
    #include "tablemodel.h"
    
    namespace Ui {
        class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private slots:
        void on_addButton_clicked();
    
    private:
        Ui::MainWindow *ui;
        QSqlDatabase db;
        TableModel *model;
    };
    
    #endif // MAINWINDOW_H
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        db = QSqlDatabase::addDatabase("QMYSQL");
        db.setHostName("127.0.0.1");
        db.setUserName("root");
        db.setPassword("damian");
        db.setDatabaseName("db_sssa");
    
        if (db.open()) {
            model = new TableModel(parent, db);
            model->setTable("employee");
            model->setEditStrategy(QSqlTableModel::OnRowChange);
            model->select();
            model->setHeaderData(0, Qt::Horizontal, tr("Id"));
            model->setHeaderData(1, Qt::Horizontal, tr("Name"));
            model->setHeaderData(2, Qt::Horizontal, tr("Age"));
            model->setHeaderData(3, Qt::Horizontal, tr("Married"));
    
            ui->tableView->setModel(model);
            ui->tableView->show();
        }
    
        connect(ui->addButton, SIGNAL (clicked()), model, SLOT (addRecord()));
    }
    
    MainWindow::~MainWindow()
    {
        db.close();
    
        delete ui;
    }
    

    If I insert a new record, it is inserted in the database table. In the view a new line appears, but with no values and I cannot edit the values.

    What am I doing wrong here?

    Thanks for your help

    1 Reply Last reply
    0
    • VRoninV Offline
      VRoninV Offline
      VRonin
      wrote on last edited by VRonin
      #2

      You are over complicating it:

      void TableModel::addRecord()
      {
          qDebug() << "addRecord";
          QSqlRecord newRecord = record();
          newRecord.setValue("id", 0);
          newRecord.setValue("id", 0);
          newRecord.setValue("name", "Enter Name");
          newRecord.setValue("gender", 0);
          newRecord.setValue("married", 0);
      
          if (insertRecord(rowCount(), newRecord)) {
              qDebug() << "New record inserted";
          }
      }
      

      from http://doc.qt.io/qt-5/qsqltablemodel.html#insertRecord:

      Calls insertRows() and setRecord() internally.

      So insertRecord will take care of inserting the row and doing the begininsertrow/endinsertrow stuff

      P.S.
      From http://doc.qt.io/qt-5/qsqldatabase.html :

      Warning: It is highly recommended that you do not keep a copy of the QSqlDatabase around as a member of a class, as this will prevent the instance from being correctly cleaned up on shutdown. If you need to access an existing QSqlDatabase, it should be accessed with database(). If you chose to have a QSqlDatabase member variable, this needs to be deleted before the QCoreApplication instance is deleted, otherwise it may lead to undefined behavior.

      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
      ~Napoleon Bonaparte

      On a crusade to banish setIndexWidget() from the holy land of Qt

      1 Reply Last reply
      4
      • I Offline
        I Offline
        Infinity
        wrote on last edited by
        #3

        I tried this. Like this the record will be inserted in the database table, but somehow the table view is not updated correctly. It looks like this
        0_1513773892452_ebfde5d5-9030-447c-a10a-2488b2f92aa5-grafik.png

        and I cannot edit the record.

        PS: Thank you for the hint of the database issue.

        1 Reply Last reply
        0

        • Login

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