Qt Quick中如何打开一个本地数据库?
发布网友
发布时间:2022-04-08 00:00
我来回答
共1个回答
热心网友
时间:2022-04-08 01:29
//打开数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("nmr.db");
if (!db.open())
{
QMessageBox::critical(0, qApp->tr("Cannot open database"),
qApp->tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information how "
"to build it.\n\n"
"Click Cancel to exit."), QMessageBox::Cancel);
return false;
}
//建个QListView显示数据库中的表
//显示数据表
void MainWindow::listDb()
{
dbListModel =new QStringListModel();
dbListModel->setStringList(QSqlDatabase::database().tables());
ui->listView->setModel(dbListModel);
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->listView->setResizeMode(QListView::Adjust);
connect(ui->listView,SIGNAL(clicked(QModelIndex)),this,SLOT(showDb(QModelIndex)));
}
//SLOT:数据显示在QTabelView控件中
void MainWindow::showDb(QModelIndex index)
{
dbName=index.data().toString();
tableViewModel=new QSqlTableModel(this);
tableViewModel->setTable(dbName);
tableViewModel->select();//???????????????????????
ui->dbTable->setSortingEnabled(true);
ui->dbTable->setModel(tableViewModel);
ui->dbTable->sortByColumn(1,Qt::AscendingOrder);
ui->dbTable->resizeColumnsToContents();
ui->dbTable->setSelectionBehavior(QAbstractItemView::SelectRows);
}