Tutorial #74: Calling function from Javascript using QtWebkit bridge

Hello everyone!

Developers often need to develop hybrid client applications that distinguish themselves from a thin client by performing heavy calculations on the client side in C++, like a native application. It presents nothing more than a QWebView for its user interface, displaying web content written in HTML/JavaScript.

In order to implement such applications Qt provides the QtWebkit-bridge that in a way extend WebKit’s JavaScript environment to access native objects represented as QObjects. Through this tutorial, we will learn how to call a native Qt function from Javascript using the webkit bridge.

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

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

Step 2: Create HTML file

First, we need to create an HTML file that will contain the Javascript code required to call our native Qt function.

test.html

<html>
<body>
<script type="text/javascript">

myoperations.display();


function displayMessage(){
    alert("Hello display");
    return "Done!";
}

myoperations.submit();

function test(){
    return "Called me!";
}
</script>

<p>Test Example to call Qt function from Javascript </p>

<input type="button" value="Click me!" onclick="displayMessage()">

</body>
</html>

Next we need to add the HTML file to our Qt project. Right click your Project –> Add Existing files and navigate to the directory where you have created the HTML file.

Step 3: Add Qt code

Let’s add the code to the main.cpp as follows. To make a method invokable, simply add the Q_INVOKABLE macro before its definition.

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>

QWebView *view;
class MyJavaScriptOperations : public QObject {
    Q_OBJECT
public:
    MyJavaScriptOperations(){

        qDebug() << "In constructor";
    }

public slots:
    Q_INVOKABLE
    void submit()
    {
        QVariant f1result = view->page()->mainFrame()->evaluateJavaScript("test()");
        qDebug() << f1result.toString();
    }

    Q_INVOKABLE void display(){

        qDebug() << "In display method";

    }

};

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

    view = new QWebView();
    view->resize(400, 500);
    view->page()->mainFrame()->addToJavaScriptWindowObject("myoperations", new MyJavaScriptOperations);
    view->load(QUrl("file:///F:/programs/test.html"));
    view->show();
    return a.exec();

}

#include "main.moc"

.pro file

QT       += core

QT       -= gui
QT       += webkit webkitwidgets
TARGET = TestHttpScriptExample
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

OTHER_FILES += \
    ../../test.html

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

output_1

output_2

Reference: Qt documentation

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