×
Namespaces

Variants
Actions
(Difference between revisions)

Fundamental use cases for porting iPhone and Android applications to Qt

From Nokia Developer Wiki
Jump to: navigation, search
ilkkal (Talk | contribs)
(Ilkkal - gameenabler mention)
hamishwillee (Talk | contribs)
m (Text replace - "<code cpp>" to "<code cpp-qt>")
(10 intermediate revisions by 2 users not shown)
Line 1: Line 1:
[[Category:Porting]][[Category:Qt]][[Category:Qt Quick]]
+
[[Category:Porting]][[Category:Qt]][[Category:Qt Quick]][[Category:MeeGo Harmattan]][[Category:Symbian]][[Category:Android]][[Category:IPhone]]
{{UnderConstruction}}
+
{{ArticleMetaData <!-- v1.2 -->
 +
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
 +
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 +
|devices= <!-- Devices tested against - e.g. ''devices=Nokia 6131 NFC, Nokia C7-00'') -->
 +
|sdk= <!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Qt SDK 1.1.4]) -->
 +
|platform= <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
 +
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 +
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
 +
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 +
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 +
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
 +
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 +
|translated-by= <!-- [[User:XXXX]] -->
 +
|translated-from-title= <!-- Title only -->
 +
|translated-from-id= <!-- Id of translated revision -->
 +
|review-by= <!-- After re-review: [[User:username]] -->
 +
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 +
|update-by= <!-- After significant update: [[User:username]]-->
 +
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 +
|creationdate= 20110622
 +
|author= [[User:Ilkkal]]
 +
}}
  
This article introduces some fundamental use cases that developers porting applications from iPhone and Android will need to implement, and discusses sample solutions. In   general, Qt provides all modern classes and functionalities familiar   from iPhone and Android. This makes it easy to keep the application   logic close to the original when porting  (see  [http://doc.qt.nokia.com/main-snapshot/classes.html Snapshot of Qt   classes]).
+
This article introduces some fundamental use cases that developers porting applications from iPhone and Android will need to implement, and discusses sample solutions. In general, Qt provides all modern classes and functionalities familiar from iPhone and Android. This makes it easy to keep the application logic close to the original when porting  (see  [http://doc.qt.nokia.com/main-snapshot/classes.html Snapshot of Qt classes]).
  
 
== Using Internet Services ==
 
== Using Internet Services ==
  
Mobile   applications are extremely likely to use the Internet — whether   loading news stories from a server, using a remote service API such as   Facebook or Twitter, or uploading photos to a photo-sharing service.  
+
Mobile applications are extremely likely to use the Internet — whether loading news stories from a server, using a remote service API such as Facebook or Twitter, or uploading photos to a photo-sharing service.  
  
While   protocols and service APIs vary considerably, it is very typical that   the traffic happens on top of the HTTP protocol and is described as XML   or JSON content.
+
While protocols and service APIs vary considerably, it is very typical that the traffic happens on top of the HTTP protocol and is described as XML or JSON content.
  
The QNetworkAccessManager  class[http://doc.qt.nokia.com/4.7/qnetworkaccessmanager.html] makes it   easy to interact with remote services. The class handles common   configuration and settings for the requests it sends, such as settings   for proxies and caching. The API is asynchronous and uses signals to   notify clients about events such as finished requests.  QNetworkAccessManager supports HTTP(S) and FTP.
+
The [http://doc.qt.nokia.com/4.7/qnetworkaccessmanager.html QNetworkAccessManager] class makes it easy to interact with remote services. The class handles common configuration and settings for the requests it sends, such as settings for proxies and caching. The API is asynchronous and uses signals to notify clients about events such as finished requests.  QNetworkAccessManager supports HTTP(S) and FTP.
  
 
A simple example of retrieving data using an URL asynchronously: (''replyFinished()'' slot is called upon completion)
 
A simple example of retrieving data using an URL asynchronously: (''replyFinished()'' slot is called upon completion)
<code cpp>
+
<code cpp-qt>
 
     ...
 
     ...
 
     QUrl url("http://www.example.com/example.xml");
 
     QUrl url("http://www.example.com/example.xml");
Line 87: Line 108:
 
== OpenGL ES Graphics using Qt GameEnabler ==
 
== OpenGL ES Graphics using Qt GameEnabler ==
  
It is easy to integrate OpenGL ES graphics into Qt applications using Qt's OpenGL module. [http://projects.developer.nokia.com/qtgameenabler Qt GameEnabler] takes the integration one step further by providing a simple starting point for game development, including not only graphics,  but also audio playback and input event handling. By downloading a Qt GameEnabler release you get a project template that you can then start customizing and extending.
+
It is easy to integrate OpenGL ES graphics into Qt applications using Qt's OpenGL module. [http://projects.developer.nokia.com/qtgameenabler Qt GameEnabler] takes the integration one step further by providing a simple starting point for game development, including not only graphics,  but also audio playback and input event handling. By downloading a Qt GameEnabler release you get a project template that you can then start customizing and extending.
  
For a step-by-step introduction to Qt Game Enabler, see [[How to utilise OpenGL ES 2.0 on Symbian^3 and Maemo#Native OpenGL with Qt application framework using Qt GameEnabler this guide]].
+
There are [http://projects.developer.nokia.com/qtgameenabler#ApplicationsBuiltwithQtGameEnabler many projects using Qt GameEnabler] hosted on the developer site that can be used for reference. One of them, [https://projects.developer.nokia.com/matchempoker Match'em Poker], also has a [https://projects.developer.nokia.com/matchempoker/wiki/porting_diary porting diary] noting the steps taken to port it from iOS to Qt.
 +
 
 +
For a step-by-step introduction to Qt Game Enabler, see [[How to utilise OpenGL ES 2.0 on Symbian^3 and Maemo#Native OpenGL with Qt application framework using Qt GameEnabler|this guide]].
 +
 
 +
== Geographic Location and Orientation ==
 +
 
 +
Qt gives developers easy access to device orientation and location data through the [http://doc.qt.nokia.com/qtmobility/location-overview.html Location] and [http://doc.qt.nokia.com/qtmobility/sensors-api.html Sensors] APIs. A good example of sensor usage is the [https://projects.developer.nokia.com/compass Compass example app] in projects. It uses orientation and compass sensors together with GPS positioning to implement a virtual compass and a map view.
 +
 
 +
To get a compass reading, the app just includes the sensors API in its project file:
 +
 
 +
<code>
 +
CONFIG += mobility
 +
MOBILITY += sensors ...
 +
</code>
 +
 
 +
Then in "mainwindow.cpp", the app creates a [http://doc.qt.nokia.com/qtmobility/qcompass.html QCompass] instance, adds a [http://doc.qt.nokia.com/qtmobility/qsensorfilter.html filter] to it and registers to receive compass reading updates:
 +
 
 +
<code cpp-qt>
 +
m_compass = new QCompass(this);
 +
m_compassFilter = new CompassFilter(this);
 +
m_compass->addFilter(m_compassFilter);
 +
...
 +
bool compassStarted = m_compass->start();
 +
...
 +
connect(m_compassFilter,
 +
        SIGNAL(azimuthChanged(const QVariant&, const QVariant&)),
 +
        rootObject, SLOT(handleAzimuth(const QVariant&, const QVariant&)));
 +
 
 +
</code>
 +
 
 +
In this case the azimuth changes are delivered straight to the root object of the QML UI, but of course the final signal handler can be something else entirely.
  
 
== Media Usage ==
 
== Media Usage ==
Line 107: Line 158:
 
Also, the common task of playing an audio file can be easily accomplished:
 
Also, the common task of playing an audio file can be easily accomplished:
  
<code cpp>
+
<code cpp-qt>
 
QSound::play("mysounds/bells.wav");
 
QSound::play("mysounds/bells.wav");
 
</code>
 
</code>
Line 119: Line 170:
 
Music file playback can be constructed as follows:
 
Music file playback can be constructed as follows:
  
<code cpp>
+
<code cpp-qt>
 
Phonon::MediaObject *music =
 
Phonon::MediaObject *music =
 
Phonon::createPlayer(Phonon::MusicCategory,
 
Phonon::createPlayer(Phonon::MusicCategory,
Line 146: Line 197:
 
== Application Data Storage ==
 
== Application Data Storage ==
  
SQLite   has changed the way you store and read data easily in mobile   applications, and there's no reason to change it. Qt allows the   application to use either the device's own SQLite database or include   one inside Qt project.
+
SQLite has changed the way you store and read data easily in mobile applications, and there's no reason to change it. Qt allows the application to use either the device's own SQLite database or include one inside Qt project.
  
In addition to features that are   familiar from iPhone and Android, Qt also provides an offline storage   API. With the offline storage API, you can use SQLite directly from QML   code with an intuitive JavaScript interface.
+
In addition to features that are familiar from iPhone and Android, Qt also provides an offline storage API. With the offline storage API, you can use SQLite directly from QML code with an intuitive JavaScript interface.
  
 
[http://doc.qt.nokia.com/4.7-snapshot/qdeclarativeglobalobject.html Read more]
 
[http://doc.qt.nokia.com/4.7-snapshot/qdeclarativeglobalobject.html Read more]
Line 154: Line 205:
 
Qt provides several different methods for storing data.
 
Qt provides several different methods for storing data.
  
Simple   data, such as application settings, is easily handled with QSettings    [http://doc.trolltech.com/main-snapshot/qsettings.html]. All details are   handled automatically:
+
Simple data, such as application settings, is easily handled with QSettings    [http://doc.trolltech.com/main-snapshot/qsettings.html]. All details are handled automatically:
<code cpp>
+
<code cpp-qt>
 
QSettings settings("CompanyName", "ApplicationName");
 
QSettings settings("CompanyName", "ApplicationName");
 
settings.setValue("store/price", 13);  
 
settings.setValue("store/price", 13);  
Line 162: Line 213:
 
</code>
 
</code>
  
More   complex data can be serialized into a binary form using QDataStream    [http://doc.trolltech.com/main-snapshot/qdatastream.html].
+
More complex data can be serialized into a binary form using QDataStream    [http://doc.trolltech.com/main-snapshot/qdatastream.html].
Serialization   of C++'s basic data types, such as char, short, int and char*, is   automatic. Serialization of more complex data is accomplished by   breaking up the data into these primitive units. An XML format for data   storage is available with QtXml    [http://doc.trolltech.com/main-snapshot/qtxml.html], which provides a   stream reader and writer for XML documents, and C++ implementations of   SAX and DOM.  
+
Serialization of C++'s basic data types, such as char, short, int and char*, is automatic. Serialization of more complex data is accomplished by breaking up the data into these primitive units. An XML format for data storage is available with QtXml    [http://doc.trolltech.com/main-snapshot/qtxml.html], which provides a stream reader and writer for XML documents, and C++ implementations of SAX and DOM.  
  
The most powerful data storage method is   QtSql [http://doc.trolltech.com/main-snapshot/qtsql.html], which   provides full SQL database functionalities. The following snippet   creates a to-do list into a local database, inserts some data there, and   reads it back selectively.
+
The most powerful data storage method is QtSql [http://doc.trolltech.com/main-snapshot/qtsql.html], which provides full SQL database functionalities. The following snippet creates a to-do list into a local database, inserts some data there, and reads it back selectively.
  
<code cpp>
+
<code cpp-qt>
 
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
 
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
 
db.setDatabaseName("myDataBase");
 
db.setDatabaseName("myDataBase");
Line 187: Line 238:
  
 
A temporary memory based database can be used by setting ':memory:' as the database name.
 
A temporary memory based database can be used by setting ':memory:' as the database name.
 
== Useful features for porting ==
 
 
This  section covers some of the most common features and examples for  porting cases, grouped by typical applications. Application sketches on  the left side of this document illustrate common application types on  iPhone and Android devices. UI component images on the right show some  of the most common Maemo/Nokia N900 elements used for building  native-like user experiences.
 
 
{|
 
|-
 
| [[File:qtexampleapps_2.jpg]]
 
|
 
{|
 
|-
 
| '''QML ListView''' The ListView element provides a list or icon view onto a model. [http://doc.qt.nokia.com/latest/qml-listview.html Read more]
 
|-
 
| '''QML Column''' The Column element provides a  vertical layout for managing other  QML elements.  [http://doc.qt.nokia.com/latest/qml-column.html Read  more]
 
|-
 
| '''Example: Dynamic linking''' Plug & Paint  example demonstrates how to write Qt applications that can be extended through dynamically loaded plugins  [http://doc.qt.nokia.com/4.7-snapshot/tools-plugandpaint.html Open]
 
|-
 
| '''Example: Server''' Fortune Server example shows how to create a server in Qt for a simple network service [http://doc.qt.nokia.com/4.7-snapshot/network-fortuneserver.html Open]
 
|-
 
| '''Feature: State Framework''' State Machine framework provides an API and execution model that can be used to easily create UI functionality in Qt applications [http://doc.qt.nokia.com/4.7-snapshot/statemachine-api.html Read more]
 
|-
 
| '''Example: State transitions''' Event Transitions example shows how to use event transitions, a feature of The State Machine Framework [http://doc.qt.nokia.com/4.7-snapshot/statemachine-eventtransitions.html Open]
 
|}
 
|}
 
 
[[File:ui-elements.png|250px|right|thumb|Common Maemo UI buttons and text elements]]
 
[[File:ui-menu.png|250px|right|thumb|Maemo UI menu]]
 
[[File:ui-gallery.png|250px|right|thumb|Sample Maemo thumbnail list]]
 
[[File:ui-portrait-buttons.png|250px|right|thumb|Common Maemo UI portrait list and buttons]]
 
[[File:ui-portrait-elements.png|250px|right|thumb|Maemo application dialog example]]
 
[[File:ui-landscape-buttons.png|250px|right|thumb|Maemo landscape list and buttons]]
 
[[File:ui-player-sample.png|250px|right|thumb|Sample Maemo application view]]
 
 
{|
 
|-
 
| [[File:qtexampleapps_3.jpg]]
 
|
 
{|
 
|-
 
| '''Feature: View transform''' By applying a transformation to the view, you can easily add support for common navigation features such as zooming and rotating [http://doc.qt.nokia.com/4.7-snapshot/graphicsview.html#zooming-and-rotating Read more]
 
|-
 
| '''Example: Drawing''' Basic Drawing    example shows how to display basic graphics primitives in a variety of    styles [http://doc.qt.nokia.com/4.7-snapshot/painting-basicdrawing.html    Open]
 
|-
 
| '''Example: Complex paths''' Painter Paths    example shows how painter paths can be used to build complex shapes for    rendering    [http://doc.qt.nokia.com/4.7-snapshot/painting-painterpaths.html Open]
 
|-
 
| '''Feature: Draw path''' Draws the given painter path using the current pen for outline and the current brush for filling [http://doc.qt.nokia.com/4.7-snapshot/qpainter.html#drawPath Read more]
 
|-
 
| '''Example: Path stroke''' Path Stroke example demonstrates various types of pens that can be used in Qt for paths [http://doc.qt.nokia.com/4.7-snapshot/demos-pathstroke.html Open]
 
|-
 
| '''Example: Advanced drawing''' Advanced Drawing example shows how to use advanced vector techniques to draw text using a QPainterPath [http://doc.qt.nokia.com/4.7-snapshot/demos-deform.html Open]
 
|}
 
|}
 
 
{|
 
|-
 
| [[File:qtexampleapps_5.jpg]]
 
|
 
{|
 
|-
 
| '''Example: XML with DOM''' QDomDocument enable developers to access the contents of XML files using a Document Object Model (DOM) API. Simple DOM Model example shows how to use it. [http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html Open]
 
|-
 
| '''Example: Image composition''' Image  Composition example demonstrates the powerful image composition features  supported in Qt.  [http://doc.qt.nokia.com/4.7-snapshot/painting-imagecomposition.html    Open]
 
|-
 
| '''Example: Advanced composition''' Composition    demo shows some of the more advanced composition modes supported by Qt  [http://doc.qt.nokia.com/4.7-snapshot/demos-composition.html Open]
 
|-
 
| '''Example: SVG viewer''' SVG Viewer example shows how to add SVG viewing support to applications for great scalable UIs and graphics. [http://doc.qt.nokia.com/4.7-snapshot/painting-svgviewer.html Open]
 
|-
 
| '''Example: State toggle''' Two-way button example shows how to use State Machine Framework to implement a logic that toggles state when a button is clicked [http://doc.qt.nokia.com/4.7-snapshot/statemachine-twowaybutton.html Open]
 
|-
 
| '''Example: State animations''' Move Blocks  example shows how to animate items in a QGraphicsScene using State  Machine Framework with a custom transition.    [http://doc.qt.nokia.com/4.7-snapshot/animation-moveblocks.html Open]
 
|-
 
| '''Example: State animations''' Application Chooser example shows how to use the Qt state machine and the animation framework. [http://doc.qt.nokia.com/4.7-snapshot/animation-appchooser.html Open]
 
|}
 
|}
 
 
{|
 
|-
 
| [[File:qtexampleapps_7.jpg]]
 
|
 
{|
 
|-
 
| '''Class: Syntax highlighting''' Syntax highlighters are often used when the user is entering text in a specific format and help the user to read the text. [http://doc.qt.nokia.com/4.7-snapshot/qsyntaxhighlighter.html Read more]
 
|-
 
| '''Example: Auto completer''' Auto-complete makes forms easier to use in mobile environments. Completer example shows how to provide string-completion facilities for an input widget based on defined data. [http://doc.qt.nokia.com/4.7-snapshot/tools-completer.html Open]
 
|-
 
| '''Example: Custom completer''' Custom Completer is an other example of how to provide string-completion facilities for an input widget[http://doc.qt.nokia.com/4.7-snapshot/tools-customcompleter.html Open]
 
|-
 
| '''Example: Google suggest''' Google Suggest    example demonstrates how to use the QNetworkAccessManager class to    obtain a list of suggestions from the Google search engine as the user    types into a QLineEdit    [http://doc.qt.nokia.com/4.7-snapshot/network-googlesuggest.html Open]
 
|-
 
| '''Example: HTTP Client''' Qt provides network-transparent features for many media and content classes, but HTTP interaction is still the very basic of modern development. HTTP example demonstrates a how to fetch files specified by URLs from remote hosts [http://doc.qt.nokia.com/4.7-snapshot/network-http.html Open]
 
|-
 
| '''Example: Web view''' Web view is a powerful tool for easy content handling. DOM Traversal example shows how to use the QWebElement class to access the structure of web view's HTML page [http://doc.qt.nokia.com/4.7-snapshot/webkit-domtraversal.html Open]
 
|-
 
| '''Example: Web view selector''' Simple Selector example shows how to use QWebElement to access the Document Object Model (DOM) in a Web page [http://doc.qt.nokia.com/4.7-snapshot/webkit-simpleselector.html Open]
 
|}
 
|}
 
 
{|
 
|-
 
| [[File:qtexampleapps_9.jpg]]
 
|
 
{|
 
|-
 
| '''QML GridView''' The GridView element allows displaying model data in a grid layout [http://doc.qt.nokia.com/latest/qml-gridview.html Read more]
 
|-
 
| '''Example: Sorting''' Custom Sort/Filter Model  example illustrates how to perform advanced sorting and filtering in Qt    [http://doc.qt.nokia.com/4.7-snapshot/itemviews-customsortfiltermodel.html  Open]
 
|-
 
| '''Example: Localization''' Qt makes    localization easy. Internationalization (I18N) example demonstrates Qt's    support for translated text    [http://doc.qt.nokia.com/4.7-snapshot/tools-i18n.html Open]
 
|-
 
| '''Example: Regexps''' Regular Expressions (RegExp) example shows how regular expressions in Qt are used with strings [http://doc.qt.nokia.com/4.7-snapshot/tools-regexp.html Open]
 
|-
 
| '''Example: SQL query''' Query Model example shows how to make customized versions of data obtained from a SQL query [http://doc.qt.nokia.com/4.7-snapshot/sql-querymodel.html Open]
 
|-
 
| '''Example: SQL drill-down''' Drill Down example shows how to read data from a database as well as submit changes [http://doc.qt.nokia.com/4.7-snapshot/sql-drilldown.html Open]
 
|}
 
|}
 
 
{|
 
|-
 
| [[File:qtexampleapps_1.jpg]]
 
|
 
{|
 
|-
 
| '''Example: Audio output''' QAudioOutput class provides an interface for sending audio data to an audio output device. Audio output example demonstrates use of this class. [http://doc.qt.nokia.com/4.7-snapshot/multimedia-audiooutput.html Open]
 
|-
 
| '''Example: Music player''' Music Player Example shows how to use Phonon - the multimedia framework that comes with Qt - to create a simple music player. [http://doc.qt.nokia.com/4.7-snapshot/phonon-qmusicplayer.html Open]
 
|-
 
| '''Example: Bearer management''' Bearer Cloud example shows how to use the Bearer Management API to monitor the connectivity state of the local device, i.e. for loading offline content only while WLAN is available [http://doc.qt.nokia.com/4.7-snapshot/network-bearercloud.html Open]
 
|}
 
|}
 
 
{|
 
|-
 
| [[File:qtexampleapps_4.jpg]]
 
|
 
{|
 
|-
 
| '''Example: Audio input''' Audio Input example  shows how to use QAudioInput class, that provides an interface for  receiving audio data from an audio input device.  [http://doc.qt.nokia.com/4.7-snapshot/multimedia-audioinput.html Open]
 
|-
 
| '''Example: Gradients'''  Gradients  Example show how the various types of gradients can be used in Qt.  [http://doc.qt.nokia.com/4.7-snapshot/demos-gradients.html Open]
 
|}
 
|}
 
 
{|
 
|-
 
| [[File:qtexampleapps_6.jpg]]
 
|
 
{|
 
|-
 
| '''Example: Drag'n'drop icons''' Drag'n'drop is the basic feature in modern user interfaces. Draggable Icons example shows how to drag and drop image data between widgets in Standard view [http://doc.qt.nokia.com/4.7-snapshot/draganddrop-draggableicons.html Open]
 
|-
 
| '''Example: Drag'n'drop text''' Draggable Text    example shows how to drag and drop textual data between widgets in    Standard view    [http://doc.qt.nokia.com/4.7-snapshot/draganddrop-draggabletext.html    Open]
 
|-
 
| '''Feature: Drag'n'drop''' Graphics View    framework provides drag and drop support for the scene, and for each and    every item    [http://doc.qt.nokia.com/4.7-snapshot/graphicsview.html#drag-and-drop    Read more]
 
|-
 
| '''Example: Fetch more''' Fetch More    example shows how two add items to an item view model on demand,    commonly used by applications with a list view    [http://doc.qt.nokia.com/4.7-snapshot/itemviews-fetchmore.html Open]
 
|-
 
| '''Example: FTP Client''' FTP Client example demonstrates how Qt can be used to list the available files on an FTP server and download them. [http://doc.qt.nokia.com/4.7-snapshot/network-qftp.html Open]
 
|-
 
| '''Example: P2P chat''' Network Chat example demonstrates a stateful peer-to-peer Chat client that uses broadcasting with QUdpSocket and QNetworkInterface to discover its peers. [http://doc.qt.nokia.com/4.7-snapshot/network-network-chat.html Open]
 
|}
 
|}
 
 
{|
 
|-
 
| [[File:qtexampleapps_8.jpg]]
 
|
 
{|
 
|-
 
| '''Example: Inline-SVG''' Text Object example shows how to reduce layout work and insert an SVG file (such as status icons, emoticons etc) into a QTextDocument [http://doc.qt.nokia.com/4.7-snapshot/richtext-textobject.html Open]
 
|-
 
| '''Example: Undo framework''' Undo Framework example shows how to easily implement advanced undo/redo functionality with the Qt undo framework [http://doc.qt.nokia.com/4.7-snapshot/tools-undoframework.html Open]
 
|-
 
| '''Feature: QtScript''' QtScript module    provides classes for making Qt applications scriptable.    [http://doc.qt.nokia.com/4.7-snapshot/qtscript.html Read more]
 
|-
 
| '''Example: Qt scripting''' Qt Scripting example demonstrates how to implement the functionality of a calculator widget [http://doc.qt.nokia.com/4.7-snapshot/script-calculator.html Open]
 
|}
 
|}
 
 
{|
 
|-
 
| [[File:qtexampleapps_10.jpg]]
 
|
 
{|
 
|-
 
| '''Example: Generated icons''' Qicon class in Qt creates automatically different button states from the given image object. Widget Icons example demonstrates how to use this great feature. [http://doc.qt.nokia.com/4.7-snapshot/widgets-icons.html Open]
 
|-
 
| '''Class: Grid layout''' QGraphicsGridLayout class provides a grid layout for managing widgets in Graphics View [http://doc.qt.nokia.com/4.7-snapshot/qgraphicsgridlayout.html Read more]
 
|-
 
| '''Feature: Painter rotate''' Adjusting    coordinate system on-the-fly makes drawing of custom layouts easier in    some cases. QPainter's rotate functionality rotates the coordinate    system the given angle clockwise.    [http://doc.qt.nokia.com/4.7-snapshot/qpainter.html#rotate ]
 
|}
 
|}
 
 
The sketches were created with [[http://balsamiq.com/products/mockups Balsamiq Mockups]].
 
 
*  See also [http://www.forum.nokia.com/Design/ Nokia Developer Design and User  Experience Guide] for ideas on how to achieve the best possible user  experience when porting your application for Nokia devices.
 

Revision as of 04:16, 11 October 2012

Article Metadata
Compatibility
Platform(s):
Symbian
Article
Created: ilkkal (22 Jun 2011)
Last edited: hamishwillee (11 Oct 2012)

This article introduces some fundamental use cases that developers porting applications from iPhone and Android will need to implement, and discusses sample solutions. In general, Qt provides all modern classes and functionalities familiar from iPhone and Android. This makes it easy to keep the application logic close to the original when porting (see Snapshot of Qt classes).

Contents

Using Internet Services

Mobile applications are extremely likely to use the Internet — whether loading news stories from a server, using a remote service API such as Facebook or Twitter, or uploading photos to a photo-sharing service.

While protocols and service APIs vary considerably, it is very typical that the traffic happens on top of the HTTP protocol and is described as XML or JSON content.

The QNetworkAccessManager class makes it easy to interact with remote services. The class handles common configuration and settings for the requests it sends, such as settings for proxies and caching. The API is asynchronous and uses signals to notify clients about events such as finished requests. QNetworkAccessManager supports HTTP(S) and FTP.

A simple example of retrieving data using an URL asynchronously: (replyFinished() slot is called upon completion)

    ...
QUrl url("http://www.example.com/example.xml");
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(url);
...
 
myClass::replyFinished(QNetworkReply *reply) {
QByteArray replyData(reply->readAll());
// Process the reply data
}

See more info at http://doc.trolltech.com/main-snapshot/qnetworkaccessmanager.html

Web View

Qt has a WebView[1] QML element for displaying web content inside the application, like iPhone and Android. Thus, your existing server-side web content is directly reusable in Qt platforms.

Here is a short example of how to use a WebView element. A website can be loaded into the element by setting its url[2] property. Note that the QtWebKit import is also required.

import QtQuick 1.0
import QtWebKit 1.0
 
WebView {
height: 640
width: 480
url: "http://www.developer.nokia.com/"
}

To get a scrolling webview, put the WebView element inside a Flickable[3] element:

import QtQuick 1.0
import QtWebKit 1.0
 
Flickable {
id: flick
width: 640
height: 480
contentWidth: web.width
contentHeight: web.height
WebView {
id: web
anchors.top: parent.top
anchors.left: parent.left
preferredWidth: flick.width
preferredHeight: flick.height
url: "http://www.developer.nokia.com"
}
}

There are a few notable things about the above example: first, the WebView gets its preferredWidth and preferredHeight properties set to the size of the Flickable, which helps the WebView to try to resize the page in an intelligent way. Second, the Flickable needs to know the size of its contents to enable flicking: this is done using the contentWidth and contentHeight properties. Third, as the actual size of the WebView changes according to the loaded page, the WebView is anchored in the Flickable only by its top and left edges.

OpenGL ES Graphics using Qt GameEnabler

It is easy to integrate OpenGL ES graphics into Qt applications using Qt's OpenGL module. Qt GameEnabler takes the integration one step further by providing a simple starting point for game development, including not only graphics, but also audio playback and input event handling. By downloading a Qt GameEnabler release you get a project template that you can then start customizing and extending.

There are many projects using Qt GameEnabler hosted on the developer site that can be used for reference. One of them, Match'em Poker, also has a porting diary noting the steps taken to port it from iOS to Qt.

For a step-by-step introduction to Qt Game Enabler, see this guide.

Geographic Location and Orientation

Qt gives developers easy access to device orientation and location data through the Location and Sensors APIs. A good example of sensor usage is the Compass example app in projects. It uses orientation and compass sensors together with GPS positioning to implement a virtual compass and a map view.

To get a compass reading, the app just includes the sensors API in its project file:

CONFIG += mobility
MOBILITY += sensors ...

Then in "mainwindow.cpp", the app creates a QCompass instance, adds a filter to it and registers to receive compass reading updates:

m_compass = new QCompass(this);
m_compassFilter = new CompassFilter(this);
m_compass->addFilter(m_compassFilter);
...
bool compassStarted = m_compass->start();
...
connect(m_compassFilter,
SIGNAL(azimuthChanged(const QVariant&, const QVariant&)),
rootObject, SLOT(handleAzimuth(const QVariant&, const QVariant&)));

In this case the azimuth changes are delivered straight to the root object of the QML UI, but of course the final signal handler can be something else entirely.

Media Usage

Many application ideas and concepts can be realised thanks to the ease and convenience of the audio/video capabilities of Qt.

Qt provides a quick and simple way to display images and simple animations using the Image and AnimatedImage class:

AnimatedImage {
source: "animations/fire.gif"
}

Also, the common task of playing an audio file can be easily accomplished:

QSound::play("mysounds/bells.wav");

For more complex cases, Qt provides the [http://doc.trolltech.com/4.7-snapshot/phonon.html Phonon multimedia framework]. Phonon provides functionality for playback of the most common multimedia formats. The media can be read from files or streamed over a network, using a QURL to a file.

Music file playback can be constructed as follows:

Phonon::MediaObject *music =
Phonon::createPlayer(Phonon::MusicCategory,
Phonon::MediaSource("/path/song.mp3"));
music->play();

For video playback, the QtMultimediaKit module[4] provides the Video QML element[5].

import QtQuick 1.0
import QtMultimediaKit 1.1
 
Rectangle {
width: 360
height: 360
Video {
source: "movie.avi"
anchors.fill: parent
}
}

Application Data Storage

SQLite has changed the way you store and read data easily in mobile applications, and there's no reason to change it. Qt allows the application to use either the device's own SQLite database or include one inside Qt project.

In addition to features that are familiar from iPhone and Android, Qt also provides an offline storage API. With the offline storage API, you can use SQLite directly from QML code with an intuitive JavaScript interface.

Read more

Qt provides several different methods for storing data.

Simple data, such as application settings, is easily handled with QSettings [6]. All details are handled automatically:

QSettings settings("CompanyName", "ApplicationName");
settings.setValue("store/price", 13);
...
int price = settings.value("store/price").toInt();

More complex data can be serialized into a binary form using QDataStream [7]. Serialization of C++'s basic data types, such as char, short, int and char*, is automatic. Serialization of more complex data is accomplished by breaking up the data into these primitive units. An XML format for data storage is available with QtXml [8], which provides a stream reader and writer for XML documents, and C++ implementations of SAX and DOM.

The most powerful data storage method is QtSql [9], which provides full SQL database functionalities. The following snippet creates a to-do list into a local database, inserts some data there, and reads it back selectively.

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("myDataBase");
 
QSqlQuery query;
query.exec("CREATE TABLE items (id int primary key, item TEXT, description TEXT)");
query.exec("INSERT INTO items values(101, 'Shopping list', 'Milk')");
query.exec("INSERT INTO items values(102, 'Shopping list', 'Beer')");
 
query.exec("SELECT * FROM items WHERE description='Beer'");
 
while (query.next()) {
QString list = query.value(1).toString();
QString item = query.value(2).toString();
qDebug() << list;
qDebug() << item;
}

A temporary memory based database can be used by setting ':memory:' as the database name.

140 page views in the last 30 days.