Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Qt Database in Large Application
    primarykey
    data
    text
    <p>I have a question regarding using Databases in Qt.</p> <p>In other languages I would do something like create a database in the main class and pass a pointer of this database to other classes to use.</p> <p>I have been playing around in Qt and it seems that if I initialize a database in the main class then I can just write and execute a query in any other class and it will use this database and I am a bit confused because there seems to be no reference to a database.</p> <p>Could someone explain this for me :)</p> <p>Here is the Database class which is instanced in MainWindow.cpp</p> <pre><code>#include "database.h" Database::Database() { Connect(); } void Database::Connect() { db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("mydatabase­.dat"); if(db.open()){ qDebug() &lt;&lt; "Connected"; } else { qDebug() &lt;&lt; "Not Connected"; } } bool Database::SetupTables() { QSqlQuery qry; qry.exec("CREATE TABLE patients ( patient_id INT, firstname VARCHAR(100), lastname VARCHAR(100) ); "); return true; } </code></pre> <p>Here is a Window (Widget) i created called PatientList </p> <pre><code>#include "patientlist.h" #include "ui_patientlist.h" #include "database.h" #include &lt;QtSql&gt; #include &lt;QtDebug&gt; PatientList::PatientList(QWidget *parent) : QWidget(parent), ui(new Ui::PatientList) { ui-&gt;setupUi(this); QSqlQuery qry; if(qry.exec("SELECT patient_id,firstname,lastname FROM patients")){ qDebug() &lt;&lt; "Success"; } else { qDebug() &lt;&lt; "Error"; } } PatientList::~PatientList() { delete ui; } </code></pre> <p>This all works fine but I just feel like im doing something wrong because I have not mentioned the database created in the MainWindow.cpp</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload