Calling an exposed QObject slot from Qt WebKit with JavaScript
Article Metadata
Tested with
Devices(s): Nokia N97, Nokia N900
Compatibility
Platform(s): Qt
Article
Keywords: Qt, web, WebKit, HTML, QWebView
Created: taaidant
(04 Dec 2009)
Last edited: hamishwillee
(05 Jul 2012)
Contents |
Overview
This snippet demonstrates how to call an exposed QObject slot from the Qt WebKit with JavaScript.
Preconditions
- Qt is installed on your platform.
- Symbian S60:
- Download Qt release from here: Qt Downloads
- Install Qt: How to Install Qt
- Maemo:
- More information about Qt on Maemo can be found here: Qt4 Maemo port
- Symbian S60:
- You've exposed the QObject as demonstrated in the article Exposing QObjects to Qt Webkit.
Code
First, we need to reference a HTML page and a JavaScript file with the resource file. Of course, the resource file must be referenced also from the project file.
WebKit_JS_slot.pro
QT += webkit
TARGET = WebKit_JS_slot
TEMPLATE = app
SOURCES += main.cpp \
mainwindow.cpp \
sampleqobject.cpp
HEADERS += mainwindow.h \
sampleqobject.h
FORMS += mainwindow.ui
RESOURCES += resources.qrc
resources.qrc
Here we reference all the required resources, like #view.html, the jquery.js helper library, and #slot.js.
<RCC>
<qresource prefix="/">
<file>view.html</file>
<file>jquery.js</file>
<file>slot.js</file>
</qresource>
</RCC>
view.html
This is the HTML that we will display in the QWebView and where we'll reference the JavaScript files.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Copyright (c) 2009 Nokia Corporation. -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<!-- You reference the resources with qrc:/ -->
<!-- JavaScript includes -->
<!-- jQuery http://jquery.com/ -->
<script type="text/javascript" src="qrc:/jquery.js" />
<!-- slot -->
<script type="text/javascript" src="qrc:/slot.js" />
<title>Slot</title>
</head>
<body>
<h1>Demonstrates slots</h1>
</body>
</html>
slot.js
/**
* This is run after the the web page has been rendered.
* $(document).ready documented here:
* http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
*/
$(document).ready(function() {
try {
var object = {intValue: 1};
/* This calls a slot which returns another object back */
var returnedObject = sampleQObject.slotThatReturns(object);
/* This outputs "1 added bonus."*/
alert(returnedObject.stringValue);
}
catch(e) {
alert(e);
}
});
Postconditions
You've successfully called an exposed QObject slot from JavaScript.


(no comments yet)