Database Connection Dialog: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
m (Wieland moved page DatabaseConnectionDialog to Database Connection Dialog: underscores)
(Cleanup)
Line 1: Line 1:
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}
{{LangSwitch}}
 
[[Category:HowTo]]
[[Category:HowTo]]
[[Category:snippets]]
[[Category:snippets]]
'''English''' | [[DatabaseConnectionDialog_German|Deutsch]]
= 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.
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.


Line 46: Line 40:
The following is the header file:
The following is the header file:


<code>/*!
<code>
/*!
  * databasedialog.h
  * databasedialog.h
  */
  */
Line 78: Line 73:
  * The display label for the database driver name.
  * The display label for the database driver name.
  */
  */
  QLabel''' labelDatabaseDriverName;
  QLabel* labelDatabaseDriverName;


/*!
/*!
Line 84: Line 79:
  * is listening for connections.
  * is listening for connections.
  */
  */
  QLabel''' labelDatabasePort;
  QLabel* labelDatabasePort;


/*!
/*!
  * The label for the database name.
  * The label for the database name.
  */
  */
  QLabel''' labelDatabaseName;
  QLabel* labelDatabaseName;


/*!
/*!
  * The label for the database host name.
  * The label for the database host name.
  */
  */
  QLabel''' labelDatabaseHostName;
  QLabel* labelDatabaseHostName;


/*!
/*!
  * The label for the database username.
  * The label for the database username.
  */
  */
  QLabel''' labelDatabaseUsername;
  QLabel* labelDatabaseUsername;


/*!
/*!
  * The label for the database password.
  * The label for the database password.
  */
  */
  QLabel''' labelDatabasePassword;
  QLabel* labelDatabasePassword;


/*!
/*!
Line 110: Line 105:
  * connection string.
  * connection string.
  */
  */
  QLabel''' labelDatabaseURL;
  QLabel* labelDatabaseURL;


/*!
/*!
Line 116: Line 111:
  * wants to connect to.
  * wants to connect to.
  */
  */
  QLineEdit''' editDatabaseName;
  QLineEdit* editDatabaseName;


/*!
/*!
  * The editable name of the database name to which connect.
  * The editable name of the database name to which connect.
  */
  */
  QLineEdit''' editDatabaseHostName;
  QLineEdit* editDatabaseHostName;


/*!
/*!
  * The database listening port.
  * The database listening port.
  */
  */
  QSpinBox''' spinBoxDatabasePort;
  QSpinBox* spinBoxDatabasePort;


/*!
/*!
  * The editable username to use for the connection.
  * The editable username to use for the connection.
  */
  */
  QLineEdit''' editDatabaseUsername;
  QLineEdit* editDatabaseUsername;


/*!
/*!
  * The editable password to use for the connection.
  * The editable password to use for the connection.
  */
  */
  QLineEdit''' editDatabasePassword;
  QLineEdit* editDatabasePassword;


/*!
/*!
Line 142: Line 137:
  * driver name and type
  * driver name and type
  */
  */
  QComboBox''' comboDatabaseDriverName;
  QComboBox* comboDatabaseDriverName;


/*!
/*!
Line 148: Line 143:
  * connect/cancel buttons.
  * connect/cancel buttons.
  */
  */
  QDialogButtonBox''' buttons;
  QDialogButtonBox* buttons;


/*!
/*!
Line 170: Line 165:


public:
public:
  explicit DatabaseConnectionDialog(QWidget '''parent = 0);
  explicit DatabaseConnectionDialog(QWidget* parent=0);


  /*!
  /*!

Revision as of 13:33, 28 June 2015

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

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,
 SIGNAL (databaseConnect(QSqlDatabase&)),
 this,
 SLOT (slotHandleNewDatabaseConnection(QSqlDatabase&)));

// 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:

/*!
 * 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>

class DatabaseConnectionDialog : public QDialog
{
 Q_OBJECT

private:

 /*!
 * The display label for the database driver name.
 */
 QLabel* labelDatabaseDriverName;

/*!
 * The display label for the TCP/IP port the database
 * is listening for connections.
 */
 QLabel* labelDatabasePort;

/*!
 * The label for the database name.
 */
 QLabel* labelDatabaseName;

/*!
 * The label for the database host name.
 */
 QLabel* labelDatabaseHostName;

/*!
 * The label for the database username.
 */
 QLabel* labelDatabaseUsername;

/*!
 * The label for the database password.
 */
 QLabel* labelDatabasePassword;

/*!
 * A label to display the summary database URL
 * connection string.
 */
 QLabel* labelDatabaseURL;

/*!
 * The editable name of the database to which the user
 * wants to connect to.
 */
 QLineEdit* editDatabaseName;

/*!
 * The editable name of the database name to which connect.
 */
 QLineEdit* editDatabaseHostName;

/*!
 * The database listening port.
 */
 QSpinBox* spinBoxDatabasePort;

/*!
 * The editable username to use for the connection.
 */
 QLineEdit* editDatabaseUsername;

/*!
 * The editable password to use for the connection.
 */
 QLineEdit* editDatabasePassword;

/*!
 * The combo from which the user can select the database
 * driver name and type
 */
 QComboBox* comboDatabaseDriverName;

/*!
 * A Dialog button box for displaying the
 * connect/cancel buttons.
 */
 QDialogButtonBox* 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:
 explicit DatabaseConnectionDialog(QWidget* parent=0);

 /*!
 * Sets the database name in the dialog.
 * dbName the name of the database
 */
 void setDatabaseName( const QString& dbName );

 /*!
 * Sets the port number for the database connection.
 * portNumber the port number the database is listening for
 * connections
 */
 void setDatabasePortNumber( int& portNumber );

 /*!
 * Sets the remote host name mnemonic name.
 * hostname the name of the host the database is running on
 */
 void setDatabaseHostName( const QString& hostname );

 /*!
 * Sets the username to use for the connection.
 * username the username to use for the connection
 */
 void setDatabaseUsername( const QString& username );

 /*!
 * Selects the driver name.
 * the driver name (therefore the database type) to
 * select in the combo box.
 */
 void setDatabaseDriverName( const QString& drvName );

 /*!
 * Sets the user password.
 * the password to use for the connection
 */
 void setDatabasePassword( const QString& pwd );


 /*!
 * Performs a check against the user data and enables/disables
 * the connect button depending on the form fill status.
 '''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.
 * 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.
 * databaseConnection the connection object
 */
 void databaseConnect( QSqlDatabase& databaseConnection );

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"

DatabaseConnectionDialog::DatabaseConnectionDialog(QWidget parent) :

QDialog(parent)

{

// 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
labelDatabaseDriverName = new QLabel( tr("Database Type (driver name)"), this );
labelDatabasePort = new QLabel( tr("TCP/IP Port Number"), this );
labelDatabaseName = new QLabel( tr("Database Name"), this );
labelDatabaseHostName = new QLabel( tr("Host Name"), this );
labelDatabaseUsername = new QLabel( tr("Username"), this );
labelDatabasePassword = new QLabel( tr("Password"), this );
labelDatabaseURL = new QLabel( this );
labelDatabaseURL->setAlignment( Qt::AlignCenter );
spinBoxDatabasePort = new QSpinBox( this );
spinBoxDatabasePort->setMaximum( 9999 );
spinBoxDatabasePort->setMinimum( 100 );
spinBoxDatabasePort->setSingleStep( 1 );
comboDatabaseDriverName = new QComboBox( this );
comboDatabaseDriverName->setEditable( false );


editDatabaseName = new QLineEdit( this );
editDatabaseHostName = new QLineEdit( this );
editDatabaseUsername = new QLineEdit( this );
editDatabasePassword = new QLineEdit( this );
editDatabasePassword->setEchoMode( QLineEdit::Password );
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
buttons = new QDialogButtonBox( this );
buttons->addButton( QDialogButtonBox::Ok );
buttons->addButton( QDialogButtonBox::Cancel );
QPushButton okButton = buttons->button( QDialogButtonBox::Ok );
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

QVBoxLayout* verticalLayout = new QVBoxLayout( this );

// create a grid layout to add all the components

QGridLayout* formGridLayout = new QGridLayout( this );
QGroupBox* gridGroupBox = new QGroupBox( this );
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

QGroupBox* urlGroupBox = new QGroupBox( this );
urlGroupBox->setTitle( tr( "Database URL" ) );
QHBoxLayout* urlLayout = new QHBoxLayout( this );
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

foreach( QString driverName, QSqlDatabase::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() )
buttons->button( QDialogButtonBox::Ok )->setEnabled( false );
else{
// enable the connect button and give focus
buttons->button( QDialogButtonBox::Ok )->setEnabled( true );
buttons->button( QDialogButtonBox::Ok )->setFocus();
}


// if the connection can be established (or at least tried)
// display the URL
if( buttons->button( QDialogButtonBox::Ok )->isEnabled() )
labelDatabaseURL->setText( comboDatabaseDriverName->currentText()
+ "://"
+ editDatabaseUsername->text()
+ "@"
+ editDatabaseHostName->text()
+ "/"
+ editDatabaseName->text() );
else
labelDatabaseURL->setText( "" );

return buttons->button( QDialogButtonBox::Ok )->isEnabled(); }

void DatabaseConnectionDialog::doDatabaseConnection() {

// check the database driver is really available
// (should never happen)
if( ! QSqlDatabase::isDriverAvailable( comboDatabaseDriverName->currentText() ) ){
QMessageBox::critical( this,
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() ){

QMessageBox::critical( this,
tr("Database Connection Error"),
databaseConnection.lastError().text()
);

// disable the connect button and set the focus again

// on the first field
buttons->button( QDialogButtonBox::Ok )->setEnabled( false );
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();

}

void DatabaseConnectionDialog::setDatabaseName(const QString &dbName) {

editDatabaseName->setText( dbName );

}

void DatabaseConnectionDialog::setDatabasePortNumber(int &portNumber) {

spinBoxDatabasePort->setValue( portNumber );

}

void DatabaseConnectionDialog::setDatabaseHostName(const QString &hostname) {

editDatabaseHostName->setText( hostname );

}

void DatabaseConnectionDialog::setDatabaseUsername(const QString &username) {

editDatabaseUsername->setText( username );

}

void DatabaseConnectionDialog::setDatabaseDriverName(const QString &drvName) {

int index = comboDatabaseDriverName->findText( drvName );
if( index >= 0 )
comboDatabaseDriverName->setCurrentIndex( index );

}

void DatabaseConnectionDialog::setDatabasePassword(const QString &pwd) {

editDatabasePassword->setText( pwd );

}

void DatabaseConnectionDialog::run(bool autoConnect) {

bool statusOk = checkFormData();
if( ! autoConnect || ! statusOk )
exec();
else
doDatabaseConnection();

}