Detect internet connection using Qt 5 framework

Hello friends!

In any software framework it is better to check internet connectivity status before making any HTTP requests to avoid HTTP exceptions. For this purpose, Qt provides developers the QNetworkInterface class. The class basically gives a listing of the host’s IP addresses and network interfaces.

In addition to that, the QNetworkAddressEntry class stores one IP address supported by a network interface, along with its associated netmask and broadcast address. It is important to note that only the IPv4 addresses are guaranteed to be listed by this class in all operating system platforms.

Through this post, we will learn how to write a simple Qt program to detect internet connection.

Pre-requisites: Qt Creator, MinGW compiler (Windows – 64 bit)

Launch Qt Creator application and create a new Qt console application project called TestInternetConnection. Choose the default Desktop kit.

Add the following code in the main.cpp file!

main.cpp

#include <QCoreApplication>
#include <QtNetwork/QNetworkInterface>

bool isConnectedToNetwork(){

    QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
    bool result = false;

    for (int i = 0; i < ifaces.count(); i++) {

        QNetworkInterface iface = ifaces.at(i);
        if ( iface.flags().testFlag(QNetworkInterface::IsUp)
             && !iface.flags().testFlag(QNetworkInterface::IsLoopBack)) {

#ifdef DEBUG
            // details of connection
            qDebug() << "name:" << iface.name() << endl
                     << "ip addresses:" << endl
                     << "mac:" << iface.hardwareAddress() << endl;
#endif


            for (int j=0; j<iface.addressEntries().count(); j++) {
#ifdef DEBUG
                qDebug() << iface.addressEntries().at(j).ip().toString()
                         << " / " << iface.addressEntries().at(j).netmask().toString() << endl;
#endif

                // got an interface which is up, and has an ip address
                if (result == false)
                    result = true;
            }
        }

    }

    return result;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextStream output(stdout);

    output << endl << "Connection Status: " << ((isConnectedToNetwork())?"Connected":"Disconnected") << endl;

    return a.exec();
}

.pro file

QT       += core

QT       -= gui
QT       += network
QT       += webkit webkitwidgets
TARGET = TestInternetConnection
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app
SOURCES += main.cpp

The allinterfaces() method returns a listing of all the network interfaces found on the host machine where as the InterfaceFlag specifies the flags associated with this network interface. Some of the possible values are,

1. QNetworkInterface::IsUp

It’s value is 0x1. It indicates whether the network interface is active.

2. QNetworkInterface::IsLoopBack

It’s value is 0x8. It indicates whether the network interface is a loopback interface, that is, it’s a virtual interface whose destination is the host computer itself.

Save all changes. Build and run the application. If no errors occur then you should see the following output!

output

Save application settings using Qt 5 framework

Hey everyone!

In one of my previous posts, we had seen how to connect to a MySQL database using Qt 5. In that case, we used database tables to store the information. However, Qt also provides the QSettings class allowing developers to save and restore application settings in a portable manner.

As mentioned in the official documentation, QSettings’s API is based on QVariant, allowing you to save most value-based types, such as QString, QRect, and QImage, with the minimum of effort. QSettings objects can be created either on the stack or on the heap (i.e. using new). Constructing and destroying a QSettings object is very fast.

Through this post, we will understand how to save our application settings using the QSettings class.

Pre-requisites: Qt Creator, MinGW compiler ( Windows – 64 bit)

Step 1: Launch Qt Creator and create a new Qt console application project called QtSettingsExample. Choose the default Desktop kit.

Step 2: Add Qt code

Let’s add the code to the main.cpp file as follows!

main.cpp

#include <QCoreApplication>
#include <QSettings>
#include <QDebug>
#include <QString>
#include <QStringList>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QSettings mysettings("CompanyXYZ","ProductABC");

    //set the settings
    mysettings.setValue("Address","Mahape");

    //set the settings with same key
    mysettings.setValue("Address","Vashi");

    //sync the settings
    mysettings.sync();

    //get the settings
    QString str1 = mysettings.value("Address").toString();

    //settings in user scope
    QSettings tempsettings(QSettings::IniFormat, QSettings::UserScope,
                          "MySoft", "Star Runner");

    QSettings inisettings("F:/programs/myapp.ini",
                       QSettings::IniFormat);

    inisettings.beginGroup("TAG1");
    QStringList content = inisettings.allKeys();

    foreach (const QString &childKey, content)
        qDebug() << "Value:" << inisettings.value(childKey).toString();

    inisettings.endGroup();

    qDebug() << "My office location is:" <<str1;
    qDebug() << "My ini file keys:" <<content;

    return a.exec();
}

.pro file

QT       += core

QT       -= gui

TARGET = QtSettingsExample
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

Note: QSettings stores settings. Each setting consists of a QString that specifies the setting’s name (the key) and a QVariant that stores the data associated with the key. To write a setting, we use the setValue() method.

Save all changes. Build and run the application. If no errors occur then you should see the following output!

output

Hope this Qt tip was useful! Stay tuned for more! 🙂

Tutorial #75: Connect to MySQL database using Qt 5 framework

Hi everyone!

Just as any other cross platform framework Qt helps to access a database, create and open one or more database connections. Qt supports a list of databases thereby providing access to the API exposed by the underlying DBMS (Database Management System). Once connected, developers can query the database using the QSqlQuery class. It can be used to execute DML (data manipulation language) statements such as SELECT, INSERT etc as well as DDL (data definition language) statements such as CREATE TABLE.

In this tutorial, we will learn how to connect to a MySQL database using the Qt 5 framework. We will also write a simple query to obtain data from our existing table.

Pre-requisites: Qt Creator, MySQL database server, MinGW compiler (Win-x64)

Step 1: Create Qt project

Launch Qt creator and create a new console application project called TestMySQLExample. Choose the default Desktop kit.

Step 2: Add Qt code

Next, you need to make changes to your main.cpp file by adding the following code. Make sure the MySQL database on your machine is up and running.

main.cpp

#include <QCoreApplication>
#include <QApplication>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QDebug>

bool createConnection();

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    if (!createConnection()){

        qDebug() << "Not connected!";
        return 1;
    }
    else{

        qDebug() << "Connected!";

        QSqlQuery query;
        query.exec("SELECT name FROM student");

        while (query.next()) {
            QString name = query.value(0).toString();
            qDebug() << "name:" << name;
        }

        return 0;
    }

    return app.exec();
}

bool createConnection(){
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("testdb");
    db.setUserName("root");
    db.setPassword("rootpassword");
    if (!db.open()) {
        qDebug() << "Database error occurred";
        return false;
    }
    return true;
}

Important: Before you compile and run the above file, you need to ensure that the libmysql.dll is present within the MySQL directory. Also check whether the path to the same has been added to your Environment Variables.

.pro file

QT       += core
QT       -= gui
QT       += webkit webkitwidgets
QT       += sql
TARGET = TestMySqlExample
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

Save all changes. Build and run the application. If no errors occur then you should see the data from your table being displayed in the console. 🙂

output

Reference: Connecting to databases in Qt

Parsing JSON using Qt 5 framework

Hello friends!

In one of my previous posts, we had seen how to send a HTTP request using Qt. The response we got then was a JSON string. JSON is a subset of the object literal notation of JavaScript. It is basically a lightweight data-interchange format making it easy for humans to read and write. A JSON is build on two structures namely,

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list or associative array.

  • An ordered list of values. In most languages, this is realized as an array, vector, list or sequence.

  • A sample valid JSON looks as follows!

    {"success":"true","controls":[{"controlID":"1","type":"TEXTBOX"},{"controlID":"4","type":"CHECKBOX"}]}
    

    An object is an un-ordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma). On the other hand, an array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

    Through this post, we will learn to parse JSON using Qt 5.

    Pre-requisites: Qt Creator, MinGW compiler (Windows – 64 bit)

    Launch Qt Creator and create a new Qt console application project called TestJsonParsing. Choose the default Desktop kit.

    Now, let’s add our JSON parser code in the main.cpp file as follows!

    main.cpp

    #include <QCoreApplication>
    #include <QDebug>
    #include <QApplication>
    #include <QtWebKitWidgets/QWebFrame>
    #include <QtWebKitWidgets/QWebPage>
    #include <QtWebKitWidgets/QWebView>
    #include <QNetworkAccessManager>
    #include <QNetworkRequest>
    #include <QNetworkReply>
    #include <QUrl>
    #include <QUrlQuery>
    #include <QWebSettings>
    #include <QVariant>
    #include <QJsonValue>
    #include <QJsonDocument>
    #include <QJsonObject>
    #include <QVariantMap>
    #include <QJsonArray>
    
    void sendRequest();
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        sendRequest();
        return a.exec();
    }
    
    void sendRequest() {
    
        // create custom temporary event loop on stack
        QEventLoop eventLoop;
    
        // "quit()" the event-loop, when the network request "finished()"
        QNetworkAccessManager mgr;
        QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    
        // the HTTP request
        QNetworkRequest req( QUrl( QString("http://time.jsontest.com/") ) );
        QNetworkReply *reply = mgr.get(req);
        eventLoop.exec(); // blocks stack until "finished()" has been called
    
        if (reply->error() == QNetworkReply::NoError) {
    
            QString strReply = (QString)reply->readAll();
    
            //parse json
            qDebug() << "Response:" << strReply;
            QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
    
            QJsonObject jsonObj = jsonResponse.object();
    
            qDebug() << "Time:" << jsonObj["time"].toString();
            qDebug() << "Date:" << jsonObj["date"].toString();
    
            delete reply;
        }
        else {
            //failure
            qDebug() << "Failure" <<reply->errorString();
            delete reply;
        }
    }
    

    .pro file

    QT       += core
    QT       -= gui
    QT       += network
    QT       += webkit webkitwidgets
    
    TARGET = TestJsonParsing
    CONFIG   += console
    CONFIG   -= app_bundle
    
    TEMPLATE = app
    
    SOURCES += main.cpp
    
    

    Save all changes. Build and run the application. If no errors are present then you should see the following output!

    qt_json_parsing

    That’s it then for this useful Qt tip. Hope it helps! 🙂

    Reference: QJsonDocument, QJsonArray

    Zipping and unzipping files using Qt 5 framework

    Hey everyone!

    Qt provides a QByteArray class that can be used to store raw bytes and traditional 8-bit terminated strings. Moreover, Qt also provides the QString class to store string data. QString is mainly used throughout the Qt API.

    Through this post, we will learn how to zip and unzip files using Qt. We will create a sample text file containing a message as follows,

    demo.txt

    This is a demo to zip and unzip files using Qt framework 
    

    Pre-requisites: Qt Creator, MinGW compiler for Windows (64 bit)

    Step 1: Launch Qt creator and create a new Qt console application project named TestZippingExample. Choose the default Desktop kit.

    Step 2: Zip and unzip files

    In order to zip files, we will be using the qCompress method of the QByteArray class. The syntax of the method is as follows,

    QByteArray qCompress ( const QByteArray & data, int compressionLevel = -1 )
    

    As mentioned in the official documentation, qCompress method compresses the data byte array and returns the compressed data in a new byte array. The compressionLevel parameter specifies how much compression should be used. Valid values are between 0 and 9, with 9 corresponding to the greatest compression (i.e. smaller compressed data) at the cost of using a slower algorithm.

    Similarly, the qUncompress method uncompresses the first n bytes of data and returns a new byte array with the uncompressed data.

    Step 3: Adding Qt code

    Open the main.cpp file and add the following code!

    main.cpp

    #include <QCoreApplication>
    #include <QByteArray>
    #include <QBitArray>
    #include <QString>
    #include <QDebug>
    #include <QFile>
    
    void Zip(QString filename , QString zipfilename);
    void Unzip(QString zipfilename , QString filename);
    
    int main(int argc, char *argv[]) {
    
        QCoreApplication a(argc, argv);
     
        //zipping
        Zip("D:\\programs\\demo.txt","D:\\programs\\demo.zip");
        qDebug() << "Done zipping";
    
        //unzipping
        Unzip("D:\\programs\\demo.zip","D:\\programs\\demo_unzipped.txt");
        qDebug() << "Done unzipping";
    
        return a.exec();
    }
    
    void Zip (QString filename , QString zipfilename){
    
        QFile infile(filename);
        QFile outfile(zipfilename);
        infile.open(QIODevice::ReadOnly);
        outfile.open(QIODevice::WriteOnly);
        QByteArray uncompressedData = infile.readAll();
        QByteArray compressedData = qCompress(uncompressedData,9);
        outfile.write(compressedData);
        infile.close();
        outfile.close();
    }
    
    void Unzip (QString zipfilename , QString filename){
        QFile infile(zipfilename);
        QFile outfile(filename);
        infile.open(QIODevice::ReadOnly);
        outfile.open(QIODevice::WriteOnly);
        QByteArray uncompressedData = infile.readAll();
        QByteArray compressedData = qUncompress(uncompressedData);
        outfile.write(compressedData);
        infile.close();
        outfile.close();
    }
    
    

    .pro file

    
    QT       += core
    
    QT       -= gui
    
    TARGET = TestZippingExample
    CONFIG   += console
    CONFIG   -= app_bundle
    
    TEMPLATE = app
    
    
    SOURCES += main.cpp
    
    

    Save all changes. Build and run the application. If no errors occur, then you should see the following output!

    zip_unzip_output

    Sending a HTTP request using Qt 5 framework

    HTTP (Hypertext Transfer Protocol) works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a web site may be the server. For example, a client (browser) submits an HTTP request to the server and then the server returns a response to the client. The response contains status information about the request as well as the requested content.

    The two commonly used methods for a request-response between a client and server are: GET and POST.

    GET – Requests data from a specified resource

    POST – Submits data to be processed to a specified resource

    The Qt framework provides the QNetworkRequest class as a part of the Network Access API that holds the information necessary to send a request over the network. As mentioned in the official API documentation, it contains a URL and some ancillary information that can be used to modify the request.

    Through this post, we will learn how to send a HTTP GET request using the Qt 5 framework!

    Pre-requisites: Qt Creator (Windows 64 bit), MinGW or VS compiler

    Launch Qt creator IDE and create a new Qt console application project called HttpGetExample. Choose the default Desktop kit and leave the Add to Version control option as None. Now, let’s write the code in our main.cpp file as follows!

    main.cpp

    #include <QCoreApplication>
    #include <QDebug>
    #include <QNetworkAccessManager>
    #include <QNetworkRequest>
    #include <QNetworkReply>
    #include <QUrl>
    #include <QUrlQuery>
    
    void sendRequest();
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        sendRequest();
        return a.exec();
    }
    
    void sendRequest(){
    
        // create custom temporary event loop on stack
        QEventLoop eventLoop;
    
        // "quit()" the event-loop, when the network request "finished()"
        QNetworkAccessManager mgr;
        QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    
        // the HTTP request
        QNetworkRequest req( QUrl( QString("http://ip.jsontest.com/") ) );
        QNetworkReply *reply = mgr.get(req);
        eventLoop.exec(); // blocks stack until "finished()" has been called
    
        if (reply->error() == QNetworkReply::NoError) {
            //success
            qDebug() << "Success" <<reply->readAll();
            delete reply;
        }
        else {
            //failure
            qDebug() << "Failure" <<reply->errorString();
            delete reply;
        }
    }
    

    You also need to make changes to the Project (.pro) file and add assign the corresponding values to variables.

    .pro file

    QT       += core
    
    QT       -= gui
    
    TARGET = HttpGetExample
    CONFIG   += console
    CONFIG   -= app_bundle
    QT += network
    TEMPLATE = app
    
    SOURCES += main.cpp
    

    Save all changes. Build and run the application. If no errors are present, then you should see the response of the HTTP request displayed in the console! 🙂

    Output

    Output

    That’s it for this small tip on Qt. Stay tuned for more! 🙂

    Reference: Inside the Qt HTTP stack

    Base64 encoding and decoding using Qt 5 framework

    Hi everyone!

    In one of my previous posts, we had learnt how to configure and setup Qt for Windows. Base64 is basically a method using which we can encode binary data into a character set in order to transmit the data without any loss or modification of the contents. It is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

    Base64-encoding is a way to encode 8 bit character data in a series of 6 bit characters. This was mostly used in transferring of data across 6 or 7 bit connections. On the other hand Base64-decoding helps us to get back the original text. Through this post, we will learn how to use the Qt framework to implement Base64 encoding and decoding.

    Pre-requisites: Qt creator for Windows (64 bit), MinGW or VS compiler

    Launch Qt Creator and create a new Qt console application project called QtEncodingExample. Choose the default Desktop kit and add the following code in the main.cpp file!

    main.cpp

    #include <QCoreApplication>
    #include <QString>
    #include <QDebug>
    #include <QByteArray>
    
    QString base64_encode(QString string);
    QString base64_decode(QString string);
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QString srcString = "Hello";
        QString encodedString = base64_encode(srcString);
        QString decodedString = base64_decode(encodedString);
    
        qDebug() << "Encoded string is" << encodedString;
        qDebug() << "Decoded string is" << decodedString;
        return a.exec();
    }
    
    QString base64_encode(QString string){
        QByteArray ba;
        ba.append(string);
        return ba.toBase64();
    }
    
    QString base64_decode(QString string){
        QByteArray ba;
        ba.append(string);
        return QByteArray::fromBase64(ba);
    }
    
    

    .pro file

    QT       += core
    
    QT       -= gui
    
    TARGET = QtEncodingExample
    CONFIG   += console
    CONFIG   -= app_bundle
    
    TEMPLATE = app
    SOURCES += main.cpp
    
    

    Save all changes. Build and run the application. If no errors occur, you should see the following output!

    qt_base64_example