Connecting to a database
In this recipe, we will learn how to connect to our SQL database using Qt's SQL module.
How to do it…
Connecting to SQL server in Qt is really simple:
First of all, open up Qt Creator and create a new Qt Widgets Application project.
Open up your project file (
.pro) and add the SQL module to your project, like so:QT += core gui sql
Next, open up
mainwindow.uiand drag seven label widgets, a combo box, and a checkbox to the canvas. Set the text properties of four of the labels toName:,Age:,Gender:, andMarried:. Then, set theobjectNameproperties of the rest toname,age,gender, andmarried. There is no need to set the object name for the previous four labels because they're for display purposes only:
After that, open up
mainwindow.hand add the following headers below theQMainWindowheader:#include <QMainWindow> #include <QtSql> #include <QSqlDatabase> #include <QSqlQuery> #include <QDebug>
Then, open up
mainwindow.cppand insert the...