General Database Connection Dialog
This code snippet shows how to implement a general database dialog that will prompt the user for general database connection properties (username, password, hostname, ecc.) as well as a combo with all available database drivers. The dialog provides also a signal that will pass the database connection (if established) so that third party components can use such connection.
Usage
Usage of the presented dialog is like the following:
- DatabaseConnectionDialog* dialog = new DatabaseConnectionDialog(this);
- // optional: set the data that will be presented to the user as auto-filled form
- dialog->setDatabaseName( "mydb" );
- dialog->setDatabasePortNumber( 1234 );
- dialog->setDatabaseHostName( "localhost" );
- dialog->setDatabaseUsername( "luca" );
- dialog->setDatabaseDriverName( "QPSQL" );
- dialog->setDatabasePassword( "pwd" );
- // enable the connect button if all the data is correct
- dialog->checkFormData();
- // connect the dialog signal to a slot where I will use the connection
- connect( dialog,
- this,
- // show the dialog (without auto-connection)
- dialog->run( false );
The dialog allows for pre-initialization of form fields, as well as an auto-connect mode that make the connection to happen automatically if all the data is in place.
Please note that this dialog can be improved in several ways, and represents therefore a starting point for a more specific database connection dialog.
Auto-Connect mode
When the run() method is invoked an autoconnect mode can be specified as boolean value true. In such mode, if all the form data is filled, the dialog immediately attempts to connect to the database, and in the case it succeed the dialog is not shown to the user and the signal is emitted. In the case the form data is not complete or the connection cannot be established, the dialog is shown to the user. If the autoconnect mode is off (parameter = false) the dialog is always shown.
Source code
The following is the header file:
- /*!
- * \file databasedialog.h
- */
- #ifndef DATABASEDIALOG_H
- #define DATABASEDIALOG_H
- #include <QDialog>
- #include <QLabel>
- #include <QLineEdit>
- #include <QComboBox>
- #include <QSpinBox>
- #include <QDialogButtonBox>
- #include <QHBoxLayout>
- #include <QVBoxLayout>
- #include <QGridLayout>
- #include <QSqlDatabase>
- #include <QString>
- #include <QMessageBox>
- #include <QDebug>
- #include <QSqlError>
- #include <QPushButton>
- #include <QGroupBox>
- {
- Q_OBJECT
- private:
- /*!
- * The display label for the database driver name.
- */
- /*!
- * The display label for the TCP/IP port the database
- * is listening for connections.
- */
- /*!
- * The label for the database name.
- */
- /*!
- * The label for the database host name.
- */
- /*!
- * The label for the database username.
- */
- /*!
- * The label for the database password.
- */
- /*!
- * A label to display the summary database URL
- * connection string.
- */
- /*!
- * The editable name of the database to which the user
- * wants to connect to.
- */
- /*!
- * The editable name of the database name to which connect.
- */
- /*!
- * The database listening port.
- */
- /*!
- * The editable username to use for the connection.
- */
- /*!
- * The editable password to use for the connection.
- */
- /*!
- * The combo from which the user can select the database
- * driver name and type
- */
- /*!
- * A Dialog button box for displaying the
- * connect/cancel buttons.
- */
- /*!
- * A method to create all the components of this dialog window
- * and lay out them correctly.
- */
- void setUpGUI();
- /*!
- * Searches for and populates the combo box with the
- * available database drivers.
- */
- void findAvailableDrivers();
- /*!
- * Performs the connection to the database
- * and emits the signal to pass the connection.
- */
- void doDatabaseConnection();
- public:
- /*!
- * Sets the database name in the dialog.
- * \param dbName the name of the database
- */
- /*!
- * Sets the port number for the database connection.
- * \param portNumber the port number the database is listening for
- * connections
- */
- void setDatabasePortNumber( int& portNumber );
- /*!
- * Sets the remote host name mnemonic name.
- * \param hostname the name of the host the database is running on
- */
- /*!
- * Sets the username to use for the connection.
- * \param username the username to use for the connection
- */
- /*!
- * Selects the driver name.
- * \param the driver name (therefore the database type) to
- * select in the combo box.
- */
- /*!
- * Sets the user password.
- * \param the password to use for the connection
- */
- /*!
- * Performs a check against the user data and enables/disables
- * the connect button depending on the form fill status.
- *\return true if the data allows a database connection
- */
- bool checkFormData();
- /*!
- * Performs the database connection or prompt the user
- * showing this dialog in the case data is not completed
- * or should not perform the autoconnection.
- * \param autoConnect if set to true tries to perform an automatic
- * connection to the database, if the data is complete, or prompt the user
- * for missing data. If set to false, simply shows the dialog and waits.
- */
- void run( bool autoConnect );
- signals:
- /*!
- * Passes the database connection in the case the connection
- * is succesful.
- * \param databaseConnection the connection object
- */
- public slots:
- /*!
- * Checks if the user has entered enough data to
- * try a database connection.
- */
- bool slotCheckFormData();
- /*!
- * Performs the database connection.
- */
- void slotPerformConnection();
- };
- #endif // DATABASEDIALOG_H
And the following is the class implementation:
- #include "databasedialog.h"
- {
- // this dialog is modal
- setModal( true );
- // the title of this dialog
- setWindowTitle( tr("Database connection") );
- // place each GUI component
- setUpGUI();
- // load available drivers
- findAvailableDrivers();
- }
- void DatabaseConnectionDialog::setUpGUI()
- {
- // create all gui components
- spinBoxDatabasePort->setMaximum( 9999 );
- spinBoxDatabasePort->setMinimum( 100 );
- spinBoxDatabasePort->setSingleStep( 1 );
- comboDatabaseDriverName->setEditable( false );
- connect( editDatabaseName,
- SIGNAL(editingFinished()),
- this,
- SLOT(slotCheckFormData()) );
- connect( editDatabaseHostName,
- SIGNAL(editingFinished()),
- this,
- SLOT(slotCheckFormData()) );
- connect( editDatabaseUsername,
- SIGNAL(editingFinished()),
- this,
- SLOT(slotCheckFormData()) );
- connect( editDatabasePassword,
- SIGNAL(editingFinished()),
- this,
- SLOT(slotCheckFormData()) );
- connect( editDatabasePassword,
- SIGNAL(returnPressed()),
- this,
- SLOT(slotCheckFormData()) );
- // create the button box
- okButton->setText( tr( "Connect!" ) );
- okButton->setEnabled( false );
- connect( buttons,
- SIGNAL(accepted()),
- this,
- SLOT(slotPerformConnection()));
- connect( buttons,
- SIGNAL(rejected()),
- this,
- SLOT(close()));
- // create a vertical layout to display components
- // create a grid layout to add all the components
- gridGroupBox->setTitle( tr("Database connection properties" ) );
- formGridLayout->addWidget( labelDatabaseDriverName, 0, 0 );
- formGridLayout->addWidget( comboDatabaseDriverName, 0, 1 );
- labelDatabaseDriverName->setBuddy( comboDatabaseDriverName );
- formGridLayout->addWidget( labelDatabaseHostName, 1, 0 );
- formGridLayout->addWidget( editDatabaseHostName, 1, 1);
- labelDatabaseHostName->setBuddy( editDatabaseHostName );
- formGridLayout->addWidget( labelDatabasePort, 2, 0 );
- formGridLayout->addWidget( spinBoxDatabasePort, 2, 1 );
- labelDatabasePort->setBuddy( spinBoxDatabasePort );
- formGridLayout->addWidget( labelDatabaseName, 3, 0 );
- formGridLayout->addWidget( editDatabaseName , 3, 1 );
- labelDatabaseName->setBuddy( editDatabaseName );
- formGridLayout->addWidget( labelDatabaseUsername, 4, 0 );
- formGridLayout->addWidget( editDatabaseUsername, 4, 1 );
- labelDatabaseUsername->setBuddy( editDatabaseUsername );
- formGridLayout->addWidget( labelDatabasePassword, 5, 0 );
- formGridLayout->addWidget( editDatabasePassword, 5, 1 );
- labelDatabasePassword->setBuddy( editDatabasePassword );
- // add all the elements to groupbox
- gridGroupBox->setLayout( formGridLayout );
- // place a new groupbox to contain the database connection URL
- urlGroupBox->setTitle( tr( "Database URL" ) );
- urlLayout->addWidget( labelDatabaseURL );
- urlGroupBox->setLayout( urlLayout );
- // nest all layouts together
- verticalLayout->addWidget( gridGroupBox );
- verticalLayout->addStretch();
- verticalLayout->addWidget( urlGroupBox );
- verticalLayout->addWidget( buttons );
- comboDatabaseDriverName->setFocus();
- }
- void DatabaseConnectionDialog::findAvailableDrivers()
- {
- // remove all items
- comboDatabaseDriverName->clear();
- // populate the combo box with all available drivers
- comboDatabaseDriverName->addItem( driverName );
- }
- bool DatabaseConnectionDialog::slotCheckFormData()
- {
- return checkFormData();
- }
- bool DatabaseConnectionDialog::checkFormData(){
- if( editDatabaseName->text().isEmpty()
- || editDatabaseHostName->text().isEmpty()
- || editDatabaseUsername->text().isEmpty()
- || editDatabasePassword->text().isEmpty() )
- else{
- // enable the connect button and give focus
- }
- // if the connection can be established (or at least tried)
- // display the URL
- labelDatabaseURL->setText( comboDatabaseDriverName->currentText()
- + "://"
- + editDatabaseUsername->text()
- + "@"
- + editDatabaseHostName->text()
- + "/"
- + editDatabaseName->text() );
- else
- labelDatabaseURL->setText( "" );
- }
- void DatabaseConnectionDialog::doDatabaseConnection()
- {
- // check the database driver is really available
- // (should never happen)
- tr("Database Connection Error"),
- tr("Database driver not available!")
- );
- return;
- }
- qDebug() << "Performing the database driver setup..";
- // set database driver properties
- QSqlDatabase databaseConnection = QSqlDatabase::addDatabase( comboDatabaseDriverName->currentText() );
- databaseConnection.setDatabaseName( editDatabaseName->text() );
- databaseConnection.setUserName( editDatabaseUsername->text() );
- databaseConnection.setHostName( editDatabaseHostName->text() );
- databaseConnection.setPassword( editDatabasePassword->text() );
- databaseConnection.setPort( spinBoxDatabasePort->text().toInt() );
- if( ! databaseConnection.open() ){
- tr("Database Connection Error"),
- databaseConnection.lastError().text()
- );
- // disable the connect button and set the focus again
- // on the first field
- editDatabaseHostName->setFocus();
- }
- else{
- // hide the dialog
- this->hide();
- // emit the signal
- qDebug() << "Emitting signal since the database is connected!";
- emit databaseConnect( databaseConnection );
- }
- }
- void DatabaseConnectionDialog::slotPerformConnection()
- {
- // perform another check against the user data
- if( slotCheckFormData() )
- doDatabaseConnection();
- }
- {
- editDatabaseName->setText( dbName );
- }
- void DatabaseConnectionDialog::setDatabasePortNumber(int &portNumber)
- {
- spinBoxDatabasePort->setValue( portNumber );
- }
- {
- editDatabaseHostName->setText( hostname );
- }
- {
- editDatabaseUsername->setText( username );
- }
- {
- int index = comboDatabaseDriverName->findText( drvName );
- if( index >= 0 )
- comboDatabaseDriverName->setCurrentIndex( index );
- }
- {
- editDatabasePassword->setText( pwd );
- }
- void DatabaseConnectionDialog::run(bool autoConnect)
- {
- bool statusOk = checkFormData();
- if( ! autoConnect || ! statusOk )
- exec();
- else
- doDatabaseConnection();
- }

