How it works…

In this example, we used two JavaScript libraries: jQuery, and Bootstrap. We also used an iconic font package called Font Awesome. These third-party add-ons were used to make the HTML user interface more interesting and responsive to different screen resolutions. We also used jQuery to detect the document's ready status, as well as to obtain the values of the input fields.

You can download jQuery from https://jquery.com/download, Bootstrap from http://getbootstrap.com/getting-started/#download, and Font Awesome from http://fontawesome.io.

Qt's WebEngine uses a mechanism called WebChannel, which enables peer-to-peer communication between the C++ program and the HTML page. The WebEngine module provides a JavaScript library that makes integration a lot easier. The JavaScript is embedded in your project's resource by default, so you don't need to import it into your project manually. You just have to include it in your HTML page by calling the following:

<script src="qrc:///qtwebchannel/qwebchannel.js"></script>

Once you have included qwebchannel.js, you can initialize the QWebChannel class and assign the Qt object we registered earlier in C++ to a JavaScript variable.

In C++, this is done as follows:

QWebChannel* webChannel = new QWebChannel();
webChannel->registerObject("mainWindow", this);
webview->page()->setWebChannel(webChannel);

Then in JavaScript, this is done as follows:

new QWebChannel(qt.webChannelTransport, function(channel) {
mainWindow = channel.objects.mainWindow;
});

You may be wondering what this line means:

qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "1234");

Qt's WebEngine uses the remote debugging method to check for JavaScript errors and other problems. The number 1234 defines the port number you want to use for remote debugging.

Once you have enabled remote debugging, you can access the debugging page by opening up a Chromium-based web browser, such as Google Chrome (this will not work in Firefox and other browsers), and type in http://127.0.0.1:1234. You will then see a page that looks like this:

The first page will display all the HTML pages that are currently running in your program, which in this case is test.html. Click on the page link and it will take you to another page for inspection. You can use this to check for CSS errors, JavaScript errors, and missing files. Note that you should disable remote debugging once your program is bug-free and ready for deployment. This is because remote debugging takes time to initialize and will increase your program's startup time.

If you want to call a C++ function from JavaScript, you must place the Q_INVOKABLE macro in front the function's declaration; otherwise, it will not work:

Q_INVOKABLE void changeQtText(QString newText);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset