n
nafab22April 30, 2019, 1:47 p.m.

Architecture Model / View

Hello everyone
I am new here so please forgive my language differences.
I am working on a learner note management software. I created a database in my software but I am stuck at the level of the information view of the database.
Here is the code

Fencene.h

#ifndef FENCENE_H
#define FENCENE_H

#include <QObject>
#include <QWidget>
#include <QGridLayout>
#include <QComboBox>
#include <QPushButton>
#include <QFormLayout>
#include <QTextEdit>
#include <QSpinBox>
#include <QGroupBox>
#include <QRadioButton>
#include <QtSql/QSqlDatabase>
#include <QMessageBox>
#include <QtSql/QSqlTableModel>
#include <QSqlQuery>
#include "logindb.h"

namespace Ui {
class FenCene;
}

class FenCene : public QWidget
{
    Q_OBJECT

public:
    explicit FenCene(QWidget *parent = nullptr, LoginDB *login = nullptr);
    ~FenCene();

private:
    Ui::FenCene *ui;
//    QSqlDatabase *db; //for my database.
    LoginDB *login;
//    QSqlTableModel *model; //join table and database
    QSqlQueryModel *model; //My problem is that I want to display some information from the SQLITE Database in view # 1.


public slots:
    void newfiledb(); // Connected to NouveauDialog in FenPrincipale.cpp
};

#endif // FENCENE_H

fencene.cpp

#include "fencene.h"
#include "ui_fencene.h"
#include <QDir>
#include <QDebug>
#include <QSqlRelationalTableModel>

FenCene::FenCene(QWidget *parent, LoginDB *loginDB) :
    QWidget(parent),
    ui(new Ui::FenCene),
    login(loginDB)
{
    ui->setupUi(this);
}


FenCene::~FenCene()
{
    delete ui;
}

void FenCene::newfiledb()
{
    /*QString path = QDir::homePath() + "/CEN.db";*/ // Home-Directory of User + Name of Database File
    // We maybe can create a subfolder in HomeDir and put .db file there later.

    //    qDebug() << path; // Output in Console to check Path to DB-File

    if(login->conOpen())
    {
        QSqlQuery query(login->db);
        query.exec("CREATE TABLE IF NOT EXISTS Student "
                   "(id INTEGER PRIMARY KEY, "
                   "name VARCHAR(30), "
                   "prename VARCHAR(50), "
                   "sex VARCHAR(1), "
                   "classID INTEGER, "
                   "FOREIGN KEY(classID) REFERENCES Class)");
        query.exec("INSERT INTO Student VALUES(NULL, 'Name0', 'Prenom0', 'M', 0)");
        query.exec("INSERT INTO Student VALUES(NULL, 'Name1', 'Prenom1', 'F', 0)");
        query.exec("INSERT INTO Student VALUES(NULL, 'Name2', 'Prenom2', 'M', 0)");


        query.exec("CREATE TABLE IF NOT EXISTS Class "         //The list of classes is in Qnouveaudialogue.ui
                   "(id INTEGER PRIMARY KEY, "                    //The name of a class is: choice (combox2) + choice (combox4) + choice (combox5).
                   "name VARCHAR(20), "          //Example: 6èmeMC1.
                   "classteacher INTEGER, "
                   "FOREIGN KEY(classteacher) REFERENCES Teacher)");
        query.exec("INSERT INTO Class VALUES(NULL, '6èmeMC1', 0)");
        query.exec("INSERT INTO Class VALUES(NULL, '6èmeMC1', 0)");
        query.exec("INSERT INTO Class VALUES(NULL, '6èmeMC1', 1)");


        query.exec("CREATE TABLE IF NOT EXISTS Teacher"   //I suggested that the teacher's name not be in the database.
                   "(id INTEGER PRIMARY KEY, "    //It's useless but I respect your instructions in the code so I put it in it.
                   "name VARCHAR(30), "
                   "prename VARCHAR(50), "
                   "sex VARCHAR(1))");
        query.exec("INSERT INTO teacher VALUES(NULL, 'NomTeacher0', 'PrenomTeacher0', 'M')");
        query.exec("INSERT INTO teacher VALUES(NULL, 'NomTeacher1', 'PrenomTeacher1', 'M')");
        query.exec("INSERT INTO teacher VALUES(NULL, 'NomTeacher2', 'PrenomTeacher2', 'M')");


        query.exec("CREATE TABLE IF NOT EXISTS Course" //(0 for Science, 1 for Litterature, 2 for Autres)
                   "(id INTEGER PRIMARY KEY, "
                   "name VARCHAR(30), "
                   "groupID INTEGER, "
                   "teacherID INTEGER, "
                   "FOREIGN KEY(groupID) REFERENCES CourseGroup, "
                   "FOREIGN KEY(teacherID) REFERENCES Teacher)");
        query.exec("INSERT INTO Course VALUES(NULL, 'CommunicationEcrite', 0, 0)"); //The list of course are in the Qnouveaudialogue
        query.exec("INSERT INTO Course VALUES(NULL, 'Lecture', 1, 0)");              //This is the combox 2
        query.exec("INSERT INTO Course VALUES(NULL, 'Anglais', 1, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'Espagnol', 1, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'Allemand', 1, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'Arabe', 1, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'Histoiregeographie', 1, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'Philosophie', 1, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'Mathematiques', 0, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'PCT', 0, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'SVT', 0, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'EPS', 2, 0)");
        query.exec("INSERT INTO Course VALUES(NULL, 'Conduite', 1, 0)");


        query.exec("CREATE TABLE IF NOT EXISTS Coursegroup"
                   "(id INTEGER PRIMARY KEY, "
                   "name VARCHAR(20))");
        query.exec("INSERT INTO Coursegroup VALUES(NULL, 'Science')");
        query.exec("INSERT INTO Coursegroup VALUES(NULL, 'Littérature')");
        query.exec("INSERT INTO Coursegroup VALUES(NULL, 'Autres')");


        query.exec("CREATE TABLE IF NOT EXISTS Grade"   // What do I have to put in this table? // This is the table which stores the students' grades
                   "(id INTEGER PRIMARY KEY, "          // Its connected to student (by the student ID) and the course (by the courseID)
                   "studentID INTEGER, "
                   "courseID INTEGER, "
                   "gradeName VARCHAR(10), "          // the "Name" of the grade is for "Notei1-5" and "Noted1-2", so you can save, which grade it is
                   "grade INTEGER, "                       // the grade value
                   "comment VARCHAR(100), "
                   "FOREIGN KEY(studentID) REFERENCES Student, "
                   "FOREIGN KEY(courseID) REFERENCES Course)");                 // additional / optional comment from teacher on this grade / note
        query.exec("INSERT INTO Grade VALUES(NULL, 0, 3, 'Test', 2, 'Comment')");  // ID N°3 FOR Espagnol
        query.exec("INSERT INTO Grade VALUES(NULL, 0, 3, 'Test2', 3, 'Comment')");
        query.exec("INSERT INTO Grade VALUES(NULL, 0, 3, 'Test3', 4, 'Comment5')");


        //// We need SQL_RelationalTableModel later to display data correctly (JOIN Tables)
        ////    QSqlRelationalTableModel *model = new QSqlRelationalTableModel(this);

        model = new QSqlQueryModel(this);
        query.exec("SELECT * FROM Student");
        model->setQuery(query);
        ui->tableView->setModel(model);
    }

    // Next I will change this function here. At the moment it still creates new tables every time and inserts our test data.

    // dont need to close in every function. DB can be connected until we dont want to view / select / delete or insert data
//    login->conClose();
}





Here is the image of the view I want to display.
The view

I specify that the columns "Moy Interro", "Moy Sem", "Moy Coef", "Mention" will be empty and are not stcoké in the database.
Thanks for your help.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

3
Evgenii Legotckoi
  • May 1, 2019, 4:48 a.m.

Hello.

It is a little bit difficult table. I can try to advice direction in this case.

Did you see this example https://evileg.com/en/post/67/

And can you show result of this code?

model = new QSqlQueryModel(this);
query.exec("SELECT * FROM Student");
model->setQuery(query);
ui->tableView->setModel(model);

I mean picture.

    n
    • May 2, 2019, 6:52 a.m.

    Hello Евгений Легоцкой
    Thank you for your reply.
    I would like to understand. So I have to create the tableview in Qt designer? And after the connected to the database?

    I will study the example that you have proposed tonight.
    Thanks again...
    Nafab

      Evgenii Legotckoi
      • May 9, 2019, 3:29 a.m.

      Yes, You can to create TableView in Qt Designer. Just find Table View object and add it to form. But you should add model to table view in c++ code.

      And yes, you can add table view and models after database connection.

        Comments

        Only authorized users can post comments.
        Please, Log in or Sign up
        e
        • ehot
        • April 1, 2024, 12:29 a.m.

        C++ - Тест 003. Условия и циклы

        • Result:78points,
        • Rating points2
        B

        C++ - Test 002. Constants

        • Result:16points,
        • Rating points-10
        B

        C++ - Test 001. The first program and data types

        • Result:46points,
        • Rating points-6
        Last comments
        k
        kmssrFeb. 9, 2024, 5:43 a.m.
        Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
        Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
        EVA
        EVADec. 25, 2023, 9:30 p.m.
        Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
        J
        JonnyJoDec. 25, 2023, 7:38 p.m.
        Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
        G
        GvozdikDec. 19, 2023, 8:01 a.m.
        Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
        Now discuss on the forum
        a
        a_vlasovApril 14, 2024, 4:41 p.m.
        Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
        Павел Дорофеев
        Павел ДорофеевApril 14, 2024, 12:35 p.m.
        QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
        f
        fastrexApril 4, 2024, 2:47 p.m.
        Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
        AC
        Alexandru CodreanuJan. 19, 2024, 10:57 p.m.
        QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

        Follow us in social networks