[英]Creating common database connection for sevaral forms using qt c++
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! 我正在创建一个简单的qt应用程序以提供详细信息并登录到该应用程序并从数据库中检索详细信息。它主要有2种形式(MainWindow和Dialog)编写了DBconncetion类以获取数据库连接! I used the DBconnection class to log into application by giving details via the MainWindow form! 我使用DBconnection类通过MainWindow表单提供详细信息来登录应用程序! 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. 但是我不知道如何保持在MainWindow窗体中打开的连接并使用它来将数据检索到Dialog窗体中的tableview。
mycode is as follows mycode如下
DBconnection.h (working successfully) DBconnection.h (成功运行)
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) MainWindow.cpp (成功运行)
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) Dialog.cpp (不起作用)
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? 如何调整代码,以便可以从MainWindow表单建立的连接中将数据检索到Dialog表单的tablewidget?
You could either pass a reference to the connection to your dialog, or make the connection static/global. 您可以将对连接的引用传递给对话框,也可以将连接设置为静态/全局。
eg1 [点拨
class Dialog()
{
DBconnection &con;
Dialog(DBconnection &con) : con(con) {};
};
Instead of a reference, you might also want to use a std::shared_ptr
. 除了参考以外,您可能还想使用std::shared_ptr
。
A nice way of making the connection global/static would be through the Service locator pattern . 使连接成为全局/静态连接的一种好方法是通过Service locator模式 。 This pattern uses a central registry known as the "service locator", which on request returns the information necessary to perform a certain task. 此模式使用称为“服务定位器”的中央注册表,该注册表根据请求返回执行特定任务所需的信息。
You might also want to have a look into things related to "Dependency injection" 您可能还想看看与“依赖注入”相关的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.