Important: Please read the Qt Code of Conduct -

Accessing database across multiple forms

  • I have two forms: Form1 and Form2. On Form1, I have:

        QSqlDatabase myDB;
    myDB = QSqlDatabase::addDatabase("QSQLITE");

    I can do anything I want with the database on Form1. Zero problems. But for adding data, deleting, editing, I created another Dialog Form to work with the data. Thing is, I can't figure out how to access myDB on Form2. I've added Form1.h to Form2.cpp, but i get an error that myDB is a private member of Form1.

    The only thing I can think of at this point is to remove the database in the function call that initiates Form2 and reopen myDB on Form2, having Form2.h and Form2.cpp setup the same way I have Form1.h and Form1.cpp. Although I haven't tried that yet, I know it'll work. But I'd like to know if there's a better way to do this. Any insight would be appreciated. Thanks.

  • Lifetime Qt Champion


    Please re-read the QSqlDatabase documentation. You should not store a local member variable of that type. QSqlDatabase already provides all the plumbing to retrieve databases connection when needed.

    Also, if you only connect to one database and use the default connection then you don't need to retrieve it on every use.

Log in to reply