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. [SOLVED] [QtSql] Create and configure a QTableView with Qt Creator
Qt 6.11 is out! See what's new in the release blog

[SOLVED] [QtSql] Create and configure a QTableView with Qt Creator

Scheduled Pinned Locked Moved General and Desktop
16 Posts 4 Posters 16.5k 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.
  • ? Offline
    ? Offline
    A Former User
    wrote on last edited by
    #7

    This should fix it:

    @model->setQuery(sql,DB); // DB is your QSqlDatabase object@

    1 Reply Last reply
    0
    • ? Offline
      ? Offline
      A Former User
      wrote on last edited by
      #8

      [quote author="HuXiKa" date="1307969159"]This should fix it:

      @model->setQuery(sql,DB); // DB is your QSqlDatabase object@[/quote]

      I'm not sure where you want me to put this. As I understand it, the db variable I used in my header connection.h is a local variable, and can't be used in another function.

      So what do I write in db? I tried including connection.h in mainwindow.cpp, but it didn't help.

      Thanks!

      1 Reply Last reply
      0
      • ? Offline
        ? Offline
        A Former User
        wrote on last edited by
        #9

        When you create database, if you provide a name, that could be passed in this call to get the db.

        @
        QSqlDatabase db = QSqlDatabase::database("QPSQL"); // like in your destructor
        @

        But, when you call setQuery without the db argument, it uses
        @
        void QSqlQueryModel::setQuery ( const QString & query, const QSqlDatabase & db = QSqlDatabase() )
        @

        the default QSqlDatabase constructor creates an invalid database.

        From Documentation

        bq. QSqlDatabase::QSqlDatabase ()
        Creates an empty, invalid QSqlDatabase object. Use addDatabase(), removeDatabase(), and database() to get valid QSqlDatabase objects.

        1 Reply Last reply
        0
        • ? Offline
          ? Offline
          A Former User
          wrote on last edited by
          #10

          Ok. So I edited the line setQuery to become:

          @model->setQuery("SELECT * FROM v_EmpAff", QSqlDatabase::database());@

          However, my tableView still is empty.

          1 Reply Last reply
          0
          • ? Offline
            ? Offline
            A Former User
            wrote on last edited by
            #11

            Hehe... you are still missing something, try giving the db name too.

            If you create database using @QSqlDatabase::addDatabase("MyDB");@

            access it using @QSqlDatabase::database("MyDB");@

            If it still doesn't work, could be some other problem in querying the data. The table view itself will work correctly.

            [Edit: "SELECT * FROM ""v_EmpAff""" -- Too many quotes?? If you need quotes in the string.. use " (\ being the escape character)..
            should be setQuery("SELECT * FROM v_EmpAff") or setQuery("SELECT * FROM "v_EmpAff"").. don't need the quotes there in SQL as far as i know..]

            1 Reply Last reply
            0
            • ? Offline
              ? Offline
              A Former User
              wrote on last edited by
              #12

              Still doesn't work. I'm reposting my most recent files.

              This is my connection.h

              @#ifndef CONNECTION_H
              #define CONNECTION_H

              #include <QMessageBox>
              #include <QtSql>

              /* Création d'une connection à la BD
              "qaimagerie", source des données
              pour l'interface. */

              static bool createConnection()
              {
              QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL", "qaimagerie"); // Définition du driver

              // Set db name, username and password to access DB
              db.setDatabaseName("qaimagerie");
              db.setUserName("*****");
              db.setPassword("*****");
              
              // Displays error if database connection fails
              if(!db.open())
              {
                  QMessageBox::critical(0, QObject::tr("Erreur de connection à la base de données"),
                                        db.lastError().text());
                  return false;
              }
              return true;
              

              }

              #endif // CONNECTION_H
              @

              And my mainwindow.cpp:

              @#include "mainwindow.h"
              #include "ui_mainwindow.h"

              MainWindow::MainWindow(QWidget *parent) :
              QMainWindow(parent),
              ui(new Ui::MainWindow)
              {
              ui->setupUi(this);

              QSqlQueryModel *model = new QSqlQueryModel;
              model->setQuery("SELECT * FROM ""v_EmpAff""", QSqlDatabase::database("qaimagerie"));
              model->setHeaderData(0, Qt::Horizontal, tr("Nom"));
              model->setHeaderData(1, Qt::Horizontal, tr("Prénom"));
              model->setHeaderData(2, Qt::Horizontal, tr("Abbr."));
              model->setHeaderData(3, Qt::Horizontal, tr("Affiliation"));
              
              ui->tableView->setModel(model);
              

              }

              MainWindow::~MainWindow()
              {
              QSqlDatabase db = QSqlDatabase::database();
              db.close();

              delete ui;
              

              }
              @

              As I understand it, when I add the DB with

              @QSqlDatabase::addDatabase("QPSQL", "qaimagerie");@

              I'm identifying the driver "QPSQL" and defining a connection name, right?

              The SQL code queries an existing view in my DB, I have checked. What could be wrong?

              1 Reply Last reply
              0
              • ? Offline
                ? Offline
                A Former User
                wrote on last edited by
                #13

                [quote author="jim_kaiser" date="1307971155"]Hehe... you are still missing something, try giving the db name too.

                If you create database using @QSqlDatabase::addDatabase("MyDB");@

                access it using @QSqlDatabase::database("MyDB");@

                If it still doesn't work, could be some other problem in querying the data. The table view itself will work correctly.

                [Edit: "SELECT * FROM ""v_EmpAff""" -- Too many quotes?? If you need quotes in the string.. use " (\ being the escape character)..
                should be setQuery("SELECT * FROM v_EmpAff") or setQuery("SELECT * FROM "v_EmpAff"").. don't need the quotes there in SQL as far as i know..][/quote]

                YES! YOU RULE! I thought I needed double quotes, because when I queried the DB using pure SQL, it complained about my capitalization and I had to make use of double quotes.

                THANKS! I've been at it for a couple of hours, only for stupid double quotes!

                On the other hand, sorting does not seem to work, but my view already specifies an ordering scheme, so I guess that's why it doesn't work.

                1 Reply Last reply
                0
                • ? Offline
                  ? Offline
                  A Former User
                  wrote on last edited by
                  #14

                  My bad, the first argument to addDatabase is the connection type and second is the name. You have that correct. You want to use PostgreSQL right? I have to test it myself to check. Can test the code with Mysql.

                  I still don't understand how this works

                  @
                  model->setQuery("SELECT * FROM ""v_EmpAff""", QSqlDatabase::database("qaimagerie"));
                  @

                  the first argument, is effectively "SELECT * FROM " "v_EmpAff" "" (3 strings)

                  Anyways, i will test your code and let you know whats wrong.

                  [Edit: Thanks, and yeah the quotes caught my eye. Not sure about the sorting and all though :P]

                  1 Reply Last reply
                  0
                  • ? Offline
                    ? Offline
                    A Former User
                    wrote on last edited by
                    #15

                    No, it's okay. It's working now.

                    Thanks a lot for your time!

                    1 Reply Last reply
                    0
                    • ? Offline
                      ? Offline
                      A Former User
                      wrote on last edited by
                      #16

                      Thats great :) Glad to help. Could you edit the title and put [Solved] in it. That's the general flow around here.

                      Happy hacking!

                      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