Same database connection for multiple forms



  • 0
    down vote
    favorite

    I am creating a simple qt application to provide details and login to the application and retrieve details from the database.It has mainly 2 forms(MainWindow and Dialog) A DBconncetion class has been written to obtain a database connection! I used the DBconnection class to log into application by giving details via the MainWindow form! but I don't know how to keep the connection that I opened in the MainWindow form and use it to retreive the data to the tableview in the Dialog form.

    mycode is as follows

    DBconnection.h (working successfully)

    public:
    QSqlDatabase mydb;
    bool connOpen(QString uname,QString pword,QString ip,int port,QString dbname){
    mydb=QSqlDatabase::addDatabase("QOCI","MyDB");
    mydb.setUserName(uname);
    mydb.setPassword(pword);
    mydb.setHostName(ip);
    mydb.setPort(port);
    mydb.setDatabaseName(dbname);
    mydb.open();
    return true;

        }
    

    MainWindow.cpp (working successfully)

    void MainWindow::on_pushButton_clicked()
    {
    DBconnection con;
    if(con.connOpen(ui->lineEdit->text(),ui->lineEdit_2->text(),ui->lineEdit_3->text(),ui->lineEdit_4->text().toInt(),ui->lineEdit_5->text())){
    Dialog dialog1;

            dialog1.setModal(true);
            dialog1.exec();
    
        }
    

    }

    Dialog.cpp (not working)

    void Dialog::on_pushButton_clicked()
    {
    QSqlQueryModel *modal = new QSqlQueryModel();
    con.connOpen();

    QSqlQuery* qry=new QSqlQuery(con.mydb);
    
    
    qry->prepare("select NAME FROM TEST1");
       qry->exec();
       modal->setQuery(*qry);
       ui->tableView->setModel(modal);
    

    }

    How can I adjust my code so that I can retrieve data to the tablewidget in Dialog form from the connection I made from the MainWindow form?

    [Locked as duplicate of https://forum.qt.io/topic/83309/connecting-to-database-when-a-form-loads-using-signals-and-slots ~kshegunov]


  • Moderators

    @Lasith Just call http://doc.qt.io/qt-5/qsqldatabase.html#database and pass the name of your connection as parameter ("MyDB" in your example).



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.