oopapidocs
2.0
|
00001 #include <QtGui> 00002 #include <QtSql> 00003 #include "ui_DbConnectionForm.h" 00004 #include "dbconnectionform.h" 00005 #include "dbconnectionsettings.h" 00006 00007 DbConnectionForm::DbConnectionForm(QWidget* parent) 00008 : QDialog(parent) 00009 { 00010 db = DbConnectionSettings::lastSaved(); 00011 ui = new Ui::DbConnectionForm(); 00012 ui->setupUi(this); 00013 00014 ui->driverCombo->clear(); 00015 ui->driverCombo->addItems(QSqlDatabase::drivers()); 00016 00017 if (!db.isValid()) return; 00018 int comboIdx = ui->driverCombo->findText(db.driverName()); 00019 if (comboIdx > 0) 00020 ui->driverCombo->setCurrentIndex(comboIdx); 00021 00022 00023 ui->passwordLineEdit->setText(db.password()); 00024 ui->hostLineEdit->setText(db.hostName()); 00025 00026 ui->userLineEdit->setText(db.userName()); 00027 QSettings s; 00028 QString path = s.value("db.path", QDesktopServices::storageLocation( 00029 QDesktopServices::DataLocation)).toString(); 00030 ui->dbFileLineEdit->setText(path); 00031 ui->databaseLineEdit->setText(db.databaseName()); 00032 QTimer::singleShot(2000, this, SLOT(on_driverCombo_activated())); 00033 } 00034 00035 bool DbConnectionForm::isFileBased() const { 00036 QString driverName = ui->driverCombo->currentText(); 00037 return !driverName.isNull() && driverName.startsWith("QSQLITE"); 00038 } 00039 00040 void DbConnectionForm::on_browseButton_clicked() { 00041 00042 QString path = ui->dbFileLineEdit->text(); 00043 QFileInfo fi(path); 00044 QDir dir = fi.absoluteDir(); 00045 00046 QFileDialog fd; 00047 fd.setFileMode(QFileDialog::AnyFile); 00048 fd.setDirectory(dir); 00049 fd.setWindowTitle("Choose a new or existing database file."); 00050 if (fd.exec()) { 00051 QStringList sl = fd.selectedFiles(); 00052 ui->dbFileLineEdit->setText(sl[0]); 00053 } 00054 } 00055 00056 00057 void DbConnectionForm::accept() { 00058 00059 // Set the default database to be this one 00060 db = QSqlDatabase::addDatabase(ui->driverCombo->currentText()); 00061 if (isFileBased()) { 00062 db.setDatabaseName(ui->dbFileLineEdit->text()); 00063 } 00064 else { 00065 db.setDatabaseName(ui->databaseLineEdit->text()); 00066 } 00067 db.setPassword(ui->passwordLineEdit->text()); 00068 db.setHostName(ui->hostLineEdit->text()); 00069 db.setUserName(ui->userLineEdit->text()); 00070 if (!db.open()) { 00071 QMessageBox::critical(this, "DB Connection failed", db.lastError().text()); 00072 } 00073 else { 00074 if (isFileBased()) { 00075 QSettings s; 00076 s.setValue("db.path", db.databaseName()); 00077 } 00078 DbConnectionSettings::save(db); 00079 QDialog::accept(); 00080 } 00081 } 00082 00083 00084 00085 void DbConnectionForm::on_driverCombo_activated(QString ) 00086 { 00087 if (isFileBased()) { 00088 ui->pwFrame->hide(); 00089 ui->fileNameFrame->show(); 00090 } 00091 else { 00092 ui->fileNameFrame->hide(); 00093 ui->pwFrame->show(); 00094 } 00095 }