You are on page 1of 204

Qt for Mobile

Tuukka Ahoniemi Technical Trainer Digia Plc

?
Thats where me and ~1499 other computerish professionals work
G lobal, based in F inland

~50 % work with mobile technologies A large, traditional S ymbian house S ince day 1, heavily involved with Q t on mobile devices

Q t Training Partner http://www.digia.com

Qt for Mobile

Objectives 1/2
To get a really good overview on
What is Q t development especially on mobile platforms
Q tMobility APIs

How do you work with the new Nokia N8

To go technical enough
To actually be able to start doing something meaningful after the course! Q t is C ++, so prior C ++ knowledge is required

If you have any questions at any point, please do not hesitate to ask! F or more information:
http://www.forum.nokia.com http://developer.qt.nokia.com
3

Qt for Mobile

Objectives 2/2
In addition to Q t basics, we will take a look at the various ways a UI can be created in Q t
To understand the variety of Qt offering for a developer!

QGraphicsView

Qt Quick

QtWebkit

CUSTOM LAF

QWidgets

NATIVE LAF

Qt for Mobile

Schedule Estimate, Day 1


Practicalities Q t Mobile O verview & S tatus Q t E ssentials F irst Q t Application Lunch Working with the Nokia Q t S DK
Tutorial

More Q t E ssentials, S ignals and S lots!


Hands-on

Q t Mobility APIs intro


Hands-on

Qt for Mobile

Schedule Estimate, Day 2


Q t Mobility APIs walkthrough
Hands-on

Porting Issues & R e-Using Platform C ode Lunch Mobile Q t UI O ffering


Q Widgets Animation F W + Hands-on G raphics V iev, Q tWebK it Q t Q uick intro!

Qt for Mobile

Required Tools
Laptop:
Q t S DK for Desktop (Windows/Linux/Mac) Nokia Q t S DK for mobile development
Includes Q t Mobility APIs Includes Q t for S ymbian and Maemo Includes Q t C reator IDE

S ymbian device (if you have one):


Q t libraries Q t Mobility libraries TR K application

Qt for Mobile

Course Material
Please copy the material from the US B stick C ontains:
C ourse slides E xercise solutions A few additional sample applications

A few N8 devices available for you to try out during the hands-on exercises!

Qt for Mobile

Qt Overview
Qt Status for Mobile Devices

What is Qt?

10

Qt for Mobile

Cross-Platform APIs
C ross-platform Q t APIs are wrappers around native services

Application 1

Application 2

Application 3

Qt APIs Qt

Qt/Windows Win32 GDI Windows Kernel

Qt/Mac Carbon / Cocoa Mac HW

Qt/Symbian S60 / OpenC Symbian

11

Qt for Mobile

Different Qt Platforms
Q t is currently ported to
Desktops: Windows, Linux (X 11), Mac Mobile platforms: E mbedded Linux, Windows C E , Maemo/MeeG o, and S ymbian

One and unified Cross-Platform API

Qt/X11

Qt/MeeGo

Qt/Win

Qt/Mac

Qt/Embedded Qt/WinCE Qt/Symbian Linux

12

Qt for Mobile

What is Qt on Mobile?

13

Qt for Mobile

What is Symbian^3?
Actually, just S ymbian (or the New S ymbian) The latest S ymbian platform release
Multiple home screens Multi-point touch HD multimedia capabilities Improved multitasking Improved graphics architecture Q t libraries pre-installed!

Nokia N8 is the first S ymbian^3 device


More devices coming out shortly! E .g. Nokia E 7

14

Qt for Mobile

Qt and the Nokia N8

The first Symbian^3 device Qt 4.6.3 (4.6.4) pre-installed Second wave of devices will have Qt 4.7 Capasitive touch screen Multi-touch and gestures work A separate GPU! HW accelerated graphics QtOpenVG rasterization mode

15

Qt for Mobile

Qt & Older Symbian Releases


Q t-based applications can potentially be run on any S ymbian platform starting from S 60 3rd E dition, F eature Pack 1
Millions of target devices out there already! However, note the lesser computing power of such devices

These older devices do not have Q t libraries pre-installed


S ymbian smart installer to the rescue! http://wiki.forum.nokia.com/index.php/Nokia_ S mart_ Installer_ for_ S ymbian

16

Qt for Mobile

Smart Installer
Your Qt app

Nokia N8 (Qt-ready!)

???

Market of Zillions of Symbian phones, BUT yet without Qt libraries

17

Qt for Mobile

Smart Installer
Your Qt app

Nokia N8 (Qt-ready!)

Smart Installer

Market of Zillions of Symbian phones, BUT yet without Qt libraries

18

Qt for Mobile

Smart Installer

Your Qt app

Check requirements
Smart Installer

Distribution .sis package

Download and install missing requirements Smart Installer server


19

Qt for Mobile

What is MeeGo?
Intels Moblin

Maemo

20

Qt for Mobile

MeeGo Architecture
Netbook UX
Netbook UI + Apps Netbook UI Framework

Handset UX

Handset UI + Apps Handset UI Framework

MeeGo API
Comms Services
Connection Mgmt ConnMan Telephony oFono VOIP, IM, Pres Telepathy Bluetooth BlueZ

Internet Services
Layout Engine WebKit Web Run-Time WebKit Web Services Lib SocialWeb Location GeoClue

Visual Services
3D Graphics OpenGL / ES 2D Graphics Cairo, QPainter I18n Rendering Pango, QText GTK /Clutter

Media Services
Media FW GStreamer Camera GStreamer plug-in Codecs GStreamer plug-in Audio PulseAudio UPnP GUPnP

Data Mgmt
Content Framework Tracker Context Framework ContextKit Package Manager PackageKit

Device Services
Device Health

Personal Services
PIM Services

Sensor Framework

Device Sync

Resource Manager

Accts & SSO

Backup & Restore

Settings Database GConf


21

Platform Info libudev


Qt for Mobile

Message Bus D-Bus

System Libraries glibc, glib

MeeGo Kernel

MeeGo Architecture
Netbook UX
Netbook UI + Apps Netbook UI Framework
QtCore, QtGui, QtNetwork, Qt Mobility APis, etc

Qt Quick

Handset UX

Handset UI + Apps Handset UI Framework Qt

MeeGo API
Media Services
Media FW GStreamer Camera GStreamer plug-in Codecs GStreamer plug-in Audio PulseAudio UPnP GUPnP

Comms Services
Connection Mgmt ConnMan Telephony oFono VOIP, IM, Pres Telepathy Bluetooth BlueZ

Internet Services
Layout Engine WebKit Web Run-Time WebKit Web Services Lib SocialWeb Location GeoClue

Visual Services
3D Graphics OpenGL / ES 2D Graphics Cairo, QPainter I18n Rendering Pango, QText GTK /Clutter

Data Mgmt
Content Framework Tracker Context Framework ContextKit Package Manager PackageKit

Device Services
Device Health

Personal Services
PIM Services

Sensor Framework

Device Sync

Resource Manager

Accts & SSO

Backup & Restore

Settings Database GConf


22

Platform Info libudev


Qt for Mobile

Message Bus D-Bus

System Libraries glibc, glib

MeeGo Kernel

Qt and All These?

==

E VE R Y WHE R E !

23

Qt for Mobile

Qt Developer Offering
Qt Quick, Qt Quick C omponents

UI
QtDeclarative QtWebkit

QtSvg

QtGUI

QtOpenGL

Engine

Qt
QtScript QtSql QtXml QtMultimedia QtCore QtXmlPatterns QtNetwork

85% of use cases **

Mobile Features Low level Native access


Native APIs

Qt Mobility APIs

S ymbian C ++
O pen C / PO S IX

Linux C /C ++ libraries

15% of use cases **

Desktop OSs

Symbian Symbian

Linux MeeGo

24

Qt for Mobile

Working with Qt on Mobile Devices


Nokia Q t S DK is the easiest approach
F ull IDE , Q t C reator All Nokia S DKs included (S ymbian, Maemo) Q t S imulator O n-device debugging (O DD)

Y ou will get plenty of hands-on exercise with this!

25

Qt for Mobile

Install Qt, Get What?


~15 modules
~ 700 API classes

Build Tools
C onfigure, qmake, moc, uic and rcc

Development Tools
Q t C reator, Q t Designer, Q t Assistant, Q t Linguist

QtOpenGl

QtOpenVG

QtSvg

QtWebKit

QtXmlPatterns

Qt3Support QtMobility APIs

QtGui

QtSql

QtXml

QtNetwork

QtScript

Phonon

QtMultimedia

QtCore

26

Qt for Mobile

Mobility API Roadmap


1.0.2
Bearer Management
(to QtNetwork in 4.7)

1.1

Later?

Service Framework

Organizer

Augmented Reality

Publish&Subscribe

Versit

Document Gallery

Face Recognition

Messaging

Sensors

Feedback

Local Connectivity (BT, NFC)

Contacts

Multimedia Telephony Events Camera


removed!

System Information

Location Landmarks, Maps, Navigation

27

Qt for Mobile

Qt Essentials

28

What is Qt Programming?
Heavily object based C ++ Hundreds of ready-made classes, names start with Q High abstraction level UIs built from widgets
= UI Building Block, derived from Q Widget

S ignalsnS lots, used for O bject-to-object communication Meta-O bjects


And Q O bject as a common base class

Parent and C hild O bjects


Memory management, window sharing

Has similarities to J ava


BUT is still C ++!

29

Qt for Mobile

Very First Application


#include <QtGui/QApplication> #include <QtGui/QLabel> int main( int argc, char** argv ) { QApplication app( argc, argv ); QLabel label( "Hetken kest elm..." ); label.show(); // or showMaximized() return app.exec(); }

30

Qt for Mobile

Building Qt Applications in General


1. qmake project
C reates a Qt project file (.pro). This can also be created manually.

2. qmake
Uses the .pro file as input and produces platform-specific Makefile(s)

3. make
C ompiles the program for the current platform E xecutes also additional tools, such as moc, uic and rcc

qmake -project

Project file (.pro)

qmake

Platform specific Makefiles

make

Application Binary

31

Qt for Mobile

Creating Your Own Qt Application


Widgets
UI building blocks, base class QWidget
Label (QLabel) O ne line text editor (QLineEdit) Main window (QMainWindow) Button (QPushButton) etc.

O ften your application UI is a composite widget which consists of multiple contained widgets
We will see plenty of examples during the course

32

Qt for Mobile

Display Widgets
Labels (Q Label) Text Browsers (Q TextBrowser) LC DNumbers (Q LC DNumber) Progress Bar (Q ProgressBar) ...and more

33

Qt for Mobile

Input & Selection Widgets


Push buttons (Q PushButton) S election buttons (Q R adioButton, Q C heckBox) Text input
Line input (Q LineE dit) Plain text input (Q PlainTextE dit) Plain & rich text input (Q TextE dit)

S pin boxes (Q S pinBox) Dial (Q Dial) S croll bars (Q S crollBar) S liders (Q S lider)

34

Qt for Mobile

Qt Assistant
Y ou can use Q t Assistant to see how to use all the widgets Provides not only profound class documentation but also good articles on Q t conventions

35

Qt for Mobile

Very First Application


#include <QtGui/QApplication> #include <QtGui/QLabel> int main( int argc, char** argv ) { QApplication app( argc, argv ); QLabel label( "Hetken kest elm..." ); label.show(); // or showMaximized() return app.exec(); }

36

Qt for Mobile

QApplication [QtGui]
Initializes application settings
Palette, font

E ncapsulates the main event loop (QApplication::exec()) Defines applications look and feel Provides localization of strings Knows applications windows
widgetAt()

Use global qApp pointer to access QApplication instance in your code


E .g. calling qApp->quit() closes the application

Derived from QCoreApplication [Q tC ore]


Used in console applications (or Q t processes without any UI, servers for instance)

37

Qt for Mobile

More Widgets?
int main( int argc, char** argv ) { QApplication app( argc, argv ); QLabel label( "Hetken kest elm..." ); label.show(); QLabel label2( "...ja sekin synkk ja ikv." ); label2.show(); return app.exec(); }

Not exactly what was intented E ach widget without a parent becomes a window of its own!
Why does S ymbian show only the latter one?

38

Qt for Mobile

QObject Class Role


Heart of Q t's object model
Base class for all object classes All Q Widgets are Q O bjects also! Provides object trees and object ownership Q O bject's responsibility is to provide a central location for the most important concepts in Q t

Has three major responsibilities


Memory Management Introspection E vent handling

39

Qt for Mobile

Parent/Child Relationship
E ach Q O bject instance may take a parent argument
C hild informs its parent about its existence, upon which the parent adds it to its own list of children

If a widget object does not have a parent, it is a window The parent widget does the following for its children:
Hides and shows children, when hidden/shown itself E nables and disables children when enabled or disabled itself

Note that a child may be explicitly hidden, although the parent is shown

40

Qt for Mobile

Memory Management
The ownership of all child Q O bjects is transferred to the parent
Automatic deletion by the parent C hildren must be allocated from the heap with the new operator! Manual deletion will not, however, cause double deletion because the child informs its parent of the deletion

All Q O bjects without a parent must be deleted manually


S tack allocation of the parent is a good option to avoid problems

O ccasionally it may seem like Q t would hold some sort of automatic garbage collection but this is not true!
Always pay attention to ownerships and responsibilities!

41

Qt for Mobile

Another Try
int main( int argc, char** argv ) { QApplication app( argc, argv ); QLabel label( "Hetken kest elm..." ); QLabel* label2 = new QLabel( "...ja sekin synkk ja ikv.", &label ); label.show(); return app.exec(); }

Nearly, but not quite enough


We need to use layouts!

42

Qt for Mobile

Grouping & Layouting Widgets


Horizontal, vertical, grid layout managers
Q HBoxLayout, Q VBoxLayout, Q G ridLayout

Tab widgets, group boxes, etc.


Q TabBar, Q G roupBox

S pacers (Q S pacerItem, blank space in layout)

43

Qt Designer
Qt for Mobile

Result

Back to Our Example: Final Try, Now With a Layout


int main( int argc, char** argv ) { QApplication app( argc, argv ); QWidget window; // Needed, cos layout can not become a window QVBoxLayout* layout = new QVBoxLayout(&window); layout->addWidget( new QLabel( "Hetken kest elm...") ); layout->addWidget( new QLabel( "...ja sekin synkk ja ikv.")); window.show(); return app.exec(); }

44

Qt for Mobile

Conclusions So Far
Widgets are put inside a main widget
Main widget becomes a parent for its child widgets No garbage collection, only ownership transfers!

Layout classes are used for non-hard-coded positioning But Do we really need to code and build everything manually?
No, of course not! ==> Nokia Q t S DK & Q t Designer

45

Qt for Mobile

Nokia Qt SDK

46

Nokia Qt SDK
S ince 4/2010 the Nokia Q t S DK has been available for all Q t-related development
Available for Windows, Linux & Mac

Includes
Q t 4.6.3 for S ymbian and Maemo Q tMobility APIs 1.0.2 Q t C reator IDE 2.0 Q t S imulator O DD for all devices E xperimental remote compilation service
Mainly aimed at Linux and Mac users wishing to compile for S ymbian However, can be used to compile for any supported target device from any Nokia Q t S DK desktop environment!
47

Qt for Mobile

Purpose of Nokia Qt SDK


All Nokia platforms under one tool
S ymbian, Maemo (, MeeG o) Install once, deploy everywhere

C ompile, deploy, execute and debug applications on all Nokia devices by just one click If you want to do builds for regular desktop environments, a separate installation of a normal Q t desktop S DK is needed as well
After this, all development can be done simply using Nokia Q t S DK !

48

Qt for Mobile

Demo: Creating New Mobile Projects

49

Qt for Mobile

Work Flow

2. Code Logic 1. Design UI

3. Try in Qt Simulator

4. Plug in device(s) and select target

50

Qt for Mobile

Work Flow

2. Code Logic 1. Design UI

3. Try in Qt Simulator

4. Plug in device(s) and select target

5. Press Play and be amazed of your Awesomeness!


Qt for Mobile

51

Back to Qt Essentials

52

Few Qt Fundamentals More Deeply


S ignals & S lots G UI Applications and layout managers C reating custom widgets using Q t Designer

53

Qt for Mobile

First, a Small GUI Example Slider


window
int main( int argc, char** argv ) { QApplication app( argc, argv ); QWidget window; QLCDNumber* lcd = new QLCDNumber( &window ); QSlider* slider = new QSlider( Qt::Horizontal, &window ); window.showMaximized(); // or show() return app.exec(); }

lcd

slider

54

Qt for Mobile

Signals and Slots


O bserver pattern Type-safe callbacks
More secure than callbacks, more flexible than virtual methods

Many-to-many relationship Implemented in Q O bject


R equires meta-object (macro Q _ O BJ E C T)

55

Qt for Mobile

Signals
A signal is a way to inform a possible observer that something of interest has happened inside the observed class
A Q PushButton is clicked
QPushButton::clicked()

An asynchronous service handler is finished


QNetworkAccessManager::finished( QNetworkReply* reply )

V alue of Q S lider is changed (and the new value is informed as a parameter)


QSlider::valueChanged( int )

S ignals are member functions that are automatically implemented in the metaobject
O nly the function declaration is provided by the developer

S ignal is sent, or emitted, using the keyword emit


emit clicked(); emit someSignal(7, Hello);

56

Qt for Mobile

Slots
A slot is a function that is to be executed when a signal has been emitted.
(When Q PushButton is clicked), close Q Dialog (When service is ready), ask for the value and store it (When Q S lider value is changed), display the value in Q LC DNumber

A S lot function is a normal member function implemented by the developer

57

Qt for Mobile

Signal and Slot Implementation


class NewClass : public QObject { Q_OBJECT // Meta-object file needed // Code convention recommends Q_OBJECT use always, // otherwise qobject_cast fails signals: // Implementation in the meta-object void newSignal(int myInt, QString myString); void anotherSignal(); public slots: // Slots are implemented as normal member functions void newSlot(int i, QString s); void someSlot(); }

58

Qt for Mobile

Connections
To receive a signal in a slot, signal and slot must be connected
bool success = QObject::connect( senderObject, SIGNAL(valueChanged(int)), observerObject, SLOT(display(int)));

E mitted signal results


In an immediate slot function call, if signal and slot implemented in objects in the same thread

S ignal and slot signatures must match (signal may have more parameters)
No compile time error checking is made!

59

Qt for Mobile

Events vs. Signals


Some Object
1. User presses button in UI
slot function

Some Object
slot function

Some Object
2. Event is generated and delivered for the corresponding objects event handler function
QEvent (mouse press)

4. Previously connected slot functions get called

slot function

Hey! Im
Event handler

QPushButton object clicked()


3. Pushbutton emits a signal clicked() to shout out loud of the situation

60

Qt for Mobile

Events vs. Signals


S o, if you C R E ATE your own widgets
Hey! Im clicked() MyWidget

Event handler Event handler Event handler

Y ou create event handlers:


What does this widget do when someone clicks it? What does it do when keyboard is pressed? What does it do when it is requested to paint itself (i.e. how does it paint itself)?

Y ou also tell, when does it emit signals

61

Qt for Mobile

Events vs. Signals


Hey! Some Object
slot function

If you US E existing widgets


SomeWidget

valueChanged()

Hey! Im clicked()

Some Object
slot function

Y ou are interested in existing signals


What do I want to do (somewhere else) when the widget is clicked()?

Y ou connect slot functions to the signals

62

Qt for Mobile

Slider Example Continued

1. S lider is moved (to value 21)

2. emit valueChanged(21)
int main( int argc, char** argv ) { QApplication app( argc, argv ); QWidget window; QLCDNumber* lcd = new QLCDNumber( &window ); QSlider* slider = new QSlider( Qt::Horizontal, &window ); QObject::connect( slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int))); window.showMaximized(); return app.exec(); }

3. display(21)

63

Qt for Mobile

Slider Example Result

Application works, but again might need a layout manager

64

Qt for Mobile

Slider Example w/ Layout Manager


int main( int argc, char** argv ) { QApplication app( argc, argv );

window
QWidget window; QVBoxLayout* layout = new QVBoxLayout( &window ); QLCDNumber* lcd = new QLCDNumber( &window ); QSlider* slider = new QSlider( Qt::Horizontal, &window ); layout->addWidget( lcd ); layout->addWidget( slider );

layout

lcd
QObject::connect( slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int))); window.showMaximized(); return app.exec(); }

slider

65

Qt for Mobile

Small GUI Example w/ Layout Result

O K, seems to work now!

66

Qt for Mobile

Summary on Qt Basics
Tree of O bjects O ne main widget acts as the parent S ignals and slots are used for making objects interact with each other Layout managers used instead of hard coded positions

Do we always need to code the whole G UI?


Nope! Lets check Q t Designer!

67

Qt for Mobile

Qt Designer

68

Qt Designer
C omes with Desktop Q t as a separate application
Also integrated to C arbide.c++ and Q tC reator, as F orm Designer

Dragndrop UI designer O utputs X ML-based .ui files .ui files are converted automatically to .h files by uic (ui compiler)
myproject.ui -> ui_ myproject.h

69

Qt for Mobile

Slider Example in Qt Designer


Add widgets with dragndrop S et Layout Modify widget properties E dit S ignals&S lots

70

Qt for Mobile

Editing Signals & Slots in Qt Designer


Y ou can connect existing signals & slots in the graphical S &S editor

71

Qt for Mobile

Lets Try It Out!


BMI C alculators layout!

72

Qt for Mobile

What Does Qt Designer Output?


Q t Designer directly manipulates a .ui file, which is XML uic will (automatically) compile the .ui file into a c++ header file
ui_ classname.h Holds a UI C onfiguration class Ui::C lassName with function setupUi that initializes an existing main window

UI Class

initialize with setupUi()

QMainWindow

73

Qt for Mobile

How to Use the Generated UI Code?


Direct approach
S imple, but no possibility to extend functionality with custom slots No means to validate input data etc.

S ingle inheritance
E xtend functionality with custom slots

74

Qt for Mobile

Direct Approach
In the .pro file, add FORMS += Slider.ui
#include ui_Slider.h int main( int argc, char** argv ) { QApplication app( argc, argv ); Ui::SliderClass ui; QMainWindow window; ui.setupUi( &window );

UI Class

initialize with setupUi()

QMainWindow
window.showMaximized(); return app.exec(); }

75

Qt for Mobile

Single Inheritance
E asy to add custom functionality with custom slot functions UI C lass becomes a member variable
#include "ui_Slider.h" class SliderApplication : public QMainWindow { Q_OBJECT public: SliderApplication(QWidget *parent = 0); ~SliderApplication(); public slots: void changeLcdColor(int value);

QMainWindow

SliderApplication UI Class

private: Ui::Slider ui; };

76

Qt for Mobile

Single Inheritance - Implementation


Slider::Slider(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect( ui.horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(changeLcdColor(int))); // Make sure the color value is correct in the beginning changeLcdColor( ui.lcdNumber->value() ); }

void Slider::changeLcdColor(int value) { QPalette pal = ui.lcdNumber->palette(); pal.setBrush( QPalette::WindowText, QBrush(QColor(value*2.55, value*2.55, value*2.55)) ); ui.lcdNumber->setPalette(pal); }

Dragging the slider now also changes the color of the LCD Number (from black to white)
77

Qt for Mobile

Work Flow, Remember?

2. Code Logic 1. Design UI

3. Try in Qt Simulator

4. Plug in device(s) and select target

5. Press Play and be amazed of your Awesomeness!


Qt for Mobile

78

Work Flow, Concretely!

1. Design UI

79

Qt for Mobile

Work Flow, Concretely!

2. Code Logic 1. Design UI

80

Qt for Mobile

Work Flow, Concretely

2. Code Logic 1. Design UI

3. Try in Qt Simulator

81

Qt for Mobile

Qt Simulator
Try out UI in phone LAF S imulate mobile events O nly for quick-testing!

82

Qt for Mobile

Work Flow, Concretely

2. Code Logic 1. Design UI

3. Try in Qt Simulator

4. Plug in device(s) and select target

83

Qt for Mobile

Configuring the Devices


The first time, youll need
F or symbian, install TR K (comes with S DK), for O DD F or maemo, configure MADDE connection F or any device, install Q t (+ Q tMobility) libraries
O r! Use smart-installer

F ind Getting Started with Nokia Qt SDK documentation for instructions

O VI S uite (or older PC S uite) is also required for the data connection between Nokia device and your device

84

Qt for Mobile

Work Flow, Concretely

2. Code Logic 1. Design UI

3. Try in Qt Simulator

4. Plug in device(s) and select target

5. Press Play and be amazed of your Awesomeness!


Qt for Mobile

85

Qt Simulator
Try out UI in phone LAF S imulate mobile events O nly for quick-testing!

86

Qt for Mobile

Configuring Device Connections


The first time, youll need
F or S ymbian, install the TR K application to your device (comes with S DK)
Used for connecting the device to Q t C reator (and for O DD as well)

F or Maemo, configure MADDE connection


O ut of scope for this course, see Nokia Q t S DK documentation for details

F or any device (other than the N8), install Q t (+ Q tMobility) libraries


Or: use smart-installer!

F ind Getting Started with Nokia Qt SDK documentation for instructions

O VI S uite (or older PC S uite) is also required for the data connection between Nokia device and your device
87

Qt for Mobile

Hands-On, Try It Out!


C reate a simple mobile Q t application
C reate the infamous Polish C urrency C onverter! O r use Q t Designer to create a simple UI with whatever you wish (a button, a slider, anything you like)
Write a little bit of logic so that your application reacts to UI events (button clicks etc.)

Make it work!
Try out in the simulator first R un on a real device as well!

88

Qt for Mobile

Qt Mobility APIs
Introduction

89

Background
Q t is originally designed for desktop O S s
O riginally no APIs for mobile device related features

Q tMobility APIs will fill this gap


C ross-platform solution, and not only for mobile O S s! In Q t Labs phase
Heavily under development At the moment ~10 APIs published

Latest version 1.0.2


1.1 beta available!

90

Qt for Mobile

Mobility API Roadmap


1.0.2
Bearer Management
(to QtNetwork in 4.7)

1.1

Later?

Service Framework

Organizer

Augmented Reality

Publish&Subscribe

Versit

Document Gallery

Face Recognition

Messaging

Sensors

Feedback

Local Connectivity (BT, NFC)

Contacts

Multimedia Telephony Events Camera


removed!

System Information

Location Landmarks, Maps, Navigation

91

Qt for Mobile

Status at 1.0.2

92

Qt for Mobile

Status at 1.1.0

*) Backend not enabled in pre-built packages


93

Qt for Mobile

Installation
C omes with Nokia Q t S DK S imply install the provided .sis file to the device

94

Qt for Mobile

First Intro to Mobility APIs


Were using class QSystemInfo from the System Information API
#include <QtGui/QApplication> #include <QtGui/QLabel> #include <qsysteminfo.h> QTM_USE_NAMESPACE;

In Symbian, well need to use #include <qsysteminfo.h> elsewhere #include <QSystemInfo> is ok

int main( int argc, char *argv[] ) { QApplication app( argc, argv ); QSystemInfo s; QLabel *label = new QLabel( "Current language is "+ s.currentLanguage() + " and you're using Qt " + s.version(QSystemInfo::QtCore) ); label->show(); return app.exec(); }

95

Qt for Mobile

First Intro to Mobility APIs


Equivivalent to using namespace QtMobility;
#include <QtGui/QApplication> #include <QtGui/QLabel> #include <qsysteminfo.h> QTM_USE_NAMESPACE;

int main( int argc, char *argv[] ) { QApplication app( argc, argv ); QSystemInfo s; QLabel *label = new QLabel( "Current language is "+ s.currentLanguage() + " and you're using Qt " + s.version(QSystemInfo::QtCore) ); label->show(); return app.exec(); }

All classes within Mobility APIs are placed inside namespace QtMobility. You can raise the whole namespace or either use syntax QtMobility::<ClassName>, like QtMobility::QSystemInfo

96

Qt for Mobile

Mobilizing the Project File


TEMPLATE = app TARGET = DEPENDPATH += . INCLUDEPATH += . CONFIG += mobility MOBILITY += systeminfo # Input SOURCES += main.cpp

97

Qt for Mobile

Compiling
Nokia Q t S DK

Windows (with mingw32-make)


qmake mingw32-make release

S ymbian
qmake make release-gcce To create/install the .sis createpackage i hw_template.pkg release-gcce

98

Qt for Mobile

Symbian Platform Security


All S ymbian processes need capabilities in order to access secured services
Platform is secure

Q t/S ymbian applications are S ymbian processes from the O S s point of view
Need capabilities for accessing secured services!

Many services provided by Q t Mobility APIs are secured services

99

Qt for Mobile

What Capabilities Are There?

http://developer.symbian.org/wiki/index.php/C apabilities_ (S ymbian_ S igned)

100

Qt for Mobile

How to Gain Capabilities?


Declare the needed capabilities in the .pro file:
Symbian { TARGET.CAPABILITY += Location NetworkServices }

Application needs to be signed


S elf-signing works for lightest capabilities (user grantable) S ymbian signed online for a bit heavier capabilities C heck the link on the previous slide for details

101

Qt for Mobile

Capabilities and Publishing


S igning publishable applications has been made dramatically easier Y ou can have O vi publishing do the signing for you
If User or S ystem capabilities F ree signing! (O K, registering is 1)

Private publishers do not need a publisher ID S ee http://www.forum.nokia.com/Distribute/Packaging_ and_ signing.xhtml

102

Qt for Mobile

More System Information API Classes


QSystemDeviceInfo QSystemDisplayInfo Device information (battery, power state, input method type, IME I, manufacturer, profile status etc.) Display information (color depth, brightness)

QSystemInfo

G eneral system information (like in the previous example)

QSystemNetworkInfo

Network information (network name, signal strength, network mode, etc.)

QSystemScreenSaver

Access to screen saver (inhibiting it)

QSystemStorageInfo

Memory and disk information (drive types, free space)

103

Qt for Mobile

QSystemDeviceInfo Example

S mall application to show the current profile, battery level and power status
Profile status naturally not available on Windows

Demo
104

Qt for Mobile

Using QSystemDeviceInfo Example (1/4) Window Class Header File


class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); public slots: void changePowerState( QSystemDeviceInfo::PowerState state ); void changeProfileInfo( QSystemDeviceInfo::Profile profile ); private: Ui::MainWindow *ui; QtMobility::QSystemDeviceInfo* m_device; };

105

Qt for Mobile

Using QSystemDeviceInfo Example (2/4) Constructor


MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_device( new QSystemDeviceInfo(this) ) { ui->setupUi(this); // batteryBar is a QProgressBar ui->batteryBar->setValue(m_device->batteryLevel()); changePowerState(m_device->currentPowerState()); // Self-created slot function changeProfileInfo(m_device->currentProfile()); // Self-created slot function connect( m_device, SIGNAL(batteryLevelChanged(int)), ui->batteryBar, SLOT(setValue(int)) ); connect( m_device, SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)), this, SLOT(changePowerState(QSystemDeviceInfo::PowerState))); connect( m_device, SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)), this, SLOT(changeProfileInfo(QSystemDeviceInfo::Profile))); }

106

Qt for Mobile

Using QSystemDeviceInfo (3/4) Examining the Power State


void MainWindow::changePowerState( QSystemDeviceInfo::PowerState state ) { switch( state ) { case QSystemDeviceInfo::BatteryPower: ui->stateLabel->setText( "Battery power"); break; case QSystemDeviceInfo::WallPower: ui->stateLabel->setText( "Wall power" ); break; case QSystemDeviceInfo::WallPowerChargingBattery: ui->stateLabel->setText( "Wall power and charging" ); break; default: ui->stateLabel->clear(); } }

107

Qt for Mobile

Using QSystemDeviceInfo (4/4) Examining the Profile Change


void MainWindow::changeProfileInfo( QSystemDeviceInfo::Profile profile ) { switch( profile ) { case QSystemDeviceInfo::SilentProfile: ui->profileLabel->setText( "Silent" ); break; case QSystemDeviceInfo::NormalProfile: ui->profileLabel->setText( "Normal" ); break; case QSystemDeviceInfo::LoudProfile: ui->profileLabel->setText( "Loud!" ); break; case QSystemDeviceInfo::OfflineProfile: ui->profileLabel->setText( "Offline" ); break; case QSystemDeviceInfo::CustomProfile: ui->profileLabel->setText( "Custom" ); break; default: // VibProfile or PowersaveProfile are not handled separately ui->profileLabel->clear(); } }

108

Qt for Mobile

Hands-On Batterize!

S how me what youve got!


As in terms of battery level

Test using mobility APIs with a really simple application


Battery indicator!

109

Qt for Mobile

Qt Training
Day 2

110

Day 2
Mobility APIs API Walkthrough
Hands-on

Porting & R e-using platform code


Lunch!

UI Afternoon, Q t Mobile UI O ffering:


QGraphicsView Qt Quick QtWebkit

CUSTOM LAF

QWidgets

NATIVE LAF

111

Qt for Mobile

Qt Mobility APIs
API Overviews

112

Mobility API Roadmap


1.0.2
Bearer Management
(to QtNetwork in 4.7)

1.1

Later?

Service Framework

Organizer

Augmented Reality

Publish&Subscribe

Versit

Document Gallery

Face Recognition

Messaging

Sensors

Feedback

Local Connectivity (BT, NFC)

Contacts

Multimedia Telephony Events Camera


removed!

System Information

Location Landmarks, Maps, Navigation

113

Qt for Mobile

System Information API Classes, Remember?


QSystemDeviceInfo QSystemDisplayInfo Device information (battery, power state, input method type, IME I, manufacturer, profile status etc.) Display information (color depth, brightness)

QSystemInfo

G eneral system information (like in the previous example)

QSystemNetworkInfo

Network information (network name, signal strength, network mode, etc.)

QSystemScreenSaver

Access to screen saver (inhibiting it)

QSystemStorageInfo

Memory and disk information (drive types, free space)

114

Qt for Mobile

Mobility API Checklist


Mobility API libraries in the device Mobilize .pro file Include classes (with classname.h) Q TM_ US E _ NAME S PAC E ;

S ee yesterdays slides for examples!

115

Qt for Mobile

Service Framework API


Defines a unified way of finding, implementing and accessing services across multiple platforms.
C lient-server (service provider) abstraction

F unctionality can be shared between applications Developer has device independent methods for finding/using/implementing services

Picture: Q t Mobility Whitepaper, http://qt.nokia.com/files/pdf/qt-mobilitywhitepaper-1.0.0

116

Qt for Mobile

Publish & Subscribe


The Publish and S ubscribe API enables applications to read item values, navigate through and subscribe to change notifications Values are represented by a QValueSpace
Hierarchical tree of which each node or leaf can optionally contain a QVariant value
QVariant is a union data type Nodes act as Paths which can be subscribed to
Serialized QValueSpace example: /Device/Buttons = 3 /Device/Buttons/1/Name = /Device/Buttons/1/Usable /Device/Buttons/2/Name = /Device/Buttons/2/Usable /Device/Buttons/3/Name = /Device/Buttons/3/Usable

Menu = true Select = false Back = true

Access with QValueSpaceSubscriber


R ead values, receive change notifications, navigate through Q V alueS pace

New values are added with QValueSpacePublisher

117

Qt for Mobile

Messaging API
Access to messaging services
S earch and sort C reate and modify S end and retrieve Launch preferred message client

A unified interface for manipulation and storage of S MS , MMS , E mail and X MPP messages is provided

118

Qt for Mobile

Key Classes for Messaging


C omposition and manipulation of messages:
QMessage QMessageAddress

Accessing message accounts


QMessageAccount QMessageFolder

S orting and filtering


QMessageStore QMessageFilter

Accessing message services


QMessageService

119

Qt for Mobile

Creating a Message
// The developer creates a QMessage object and then sets the necessary message details. First set the message type, the default account for messages of the specified type will be used for sending : QMessage message; message.setType(QMessageAddress::Email); // Now a recipient is set : QString recipient(user@example.com); message.setTo(QMessageAddress(QMessageAddress::Email, recipient)); // For email a subject and a body are set, and any relevant attachments added : message.setSubject(Example subject); message.setBody(Example body text); QStringList attachmentPaths; attachmentPaths << images/landscape.png; message.appendAttachments(attachmentPaths);

120

Qt for Mobile

Sending the Message


// The message is ready to be sent. Next, create a service object and call the send() function QMessageService *m_service = new QMessageService(); if (!m_service->send(message)) { QMessageBox::warning(0, tr(Failed), tr(Unable to send message)); }

Opening the Default Composer


// Will open the default composer for messages of this type and with the existing message as the initial situation QMessageService *m_service = new QMessageService(); m_service->compose(message)

121

Qt for Mobile

Location API
This API provides an easy to use interface that encapsulates basic geographical information obtained from satellite or other sources about the user
Q G eoPositionInfo class contains information gathered on a global position, direction and velocity at a particular point in time

Multiple methods for receiving location data


G PS C ell ID Anything derived from Q G eoPositionInfoS ource

Also support for direct access to any NME A data


C ommon text-based protocol for navigational data

122

Qt for Mobile

Monitoring Position Data


Default position source may be available on some platforms
QGeoPositionInfoSource::createDefaultSource()

Q G eoPositionInfoS ource is simple to use


startUpdates() (and setUpdateInterval() ) positionUpdated( QGeoPositionInfo ) [signal] is emitted after each interval stopUpdates()

123

Qt for Mobile

Simple Client Receiving Location Data


class MyClass : public QObject { Q_OBJECT public: MyClass(QObject *parent = 0) : QObject(parent) { QGeoPositionInfoSource *source = QGeoPositionInfoSource::createDefaultSource(this); if (source) { connect(source, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo))); source->startUpdates(); } } private slots: void positionUpdated(const QGeoPositionInfo &info) { qDebug() << "Position updated:" << info; } };

124

Qt for Mobile

Demo! - Locationer
G et your location and send to your friend via S MS !

125

Qt for Mobile

Contacts API
The C ontacts API allows developers to manage contact data in a platform independent way.
A contact is the digital representation of a person, group or entity A contact consists of a set of contact details with own semantics of usage and storage with different context info (like separate phone number for work and home)

QContactManager unifies one or more platform-specific contact backends

126

Qt for Mobile

Main Contact Classes


QContact Addressbook contact

QContactDetail

S ingle detail of a QContact

QContactManager

Access to contacts stored in particular backend Used to select contacts through QContactManager Interface for performing actions to contacts (like S end email or Dial)

QContactFilter

QContactAction

127

Qt for Mobile

Versit API
F unctionality for reading and writing Versit documents such as vC ards
QVersitDocument QVersitReader QVersitWriter

Utilities to import/export Q C ontacts from/to Versit documents


QVersitContactImporter QVersitContactExporter

128

Qt for Mobile

Bearer Management API


Now part of Q t 4.7 Q tNetwork! Manages the connectivity state to the network
Allows user to start or stop network interfaces Is device online and how many available interfaces there are

Allows comparison and prioritization of the access and use of grouped access points When using Bearer Management the developer does not need to worry about locating the best connection
User selects best Transparent selection

Automatic roaming between cellular and WLAN networks


129

Qt for Mobile

Classes for Bearer Management


QNetworkConfiguration Abstraction of one or more access point configurations.

QNetworkConfigurationManager

Manages the network configurations provided by the system

QNetworkSession

C ontrol over the system's access points and enables session management for cases when multiple clients access the same access point

130

Qt for Mobile

Small Example on Bearer Management

Application lists available network configurations and shows information on the selected one
UI consists only of a QListView and a QTextBrowser QListView uses QStringListModel (which has the names of the configurations)

F or a more complex example, see Bearer Monitor example of the Mobility APIs
Demo
131

Qt for Mobile

Multimedia APIs
Play audio & video of various formats R ecord audio Playing and managing of an F M radio With Q tMultimedia, will eventually replace Phonon API Access to multimedia services with minimal code and maximal flexibility

132

Qt for Mobile

Overview on Multimedia API (Main Classes Only)

Included in 1.1.0

133

Qt for Mobile

Sensors API
The API supports sensors that poll for their data and sensors that push data to the app as it arrives
Application Code QSensor QSensorBackend

QSensorReading

Device Plugin

QSensor (and its subclasses) provide application with access to data input from a sensor
Direct subclass instantiation Q S ensorR eading subclasses represent single readings from a single sensor

QSensorBackend can be used to make sensors available through the same API, by creating plugins

134

Qt for Mobile

Existing QSensor Subclasses


QAccelerometer QAmbientLightSensor QCompass QMagnetometer QOrientationSensor QPromiximitySensor QRotationSensor QTapSensor Linear acceleration along the X, Y and Z axes Ambient light sensor C ompass Magnetometer O rientation Proximity (if something is close) R otation Tap sensor (registers tap and double tap events in 6 directions)

135

Qt for Mobile

Demo: Using Sensors

Proximity Sensor Test

Horizonize with Orientation sensor

136

Qt for Mobile

Now you, Adaptive Flashlight Hands-On!

S tart with the given code template


Add an ambient light sensor to the example

137

Qt for Mobile

Mobility API Roadmap


1.0.2
Bearer Management
(to QtNetwork in 4.7)

1.1

Later?

Service Framework

Organizer

Augmented Reality

Publish&Subscribe

Versit

Document Gallery

Face Recognition

Messaging

Sensors

Feedback

Local Connectivity (BT, NFC)

Contacts

Multimedia Telephony Events Camera


removed!

System Information

Location Landmarks, Maps, Navigation

138

Qt for Mobile

Porting Mobile Applications to Qt

139

Contents
Different Application Approaches in Nokia Devices Porting from iPhone or Android to Q t, no code re-use
Mapping concepts

Porting from native S ymbian/Maemo to Q t, how to re-use platform code


Porting Alternatives:
Hybrid UI E ngine Wrapping

140

Qt for Mobile

Different Application Approaches in Nokia Devices


WEB

Qt C++

WEB

Qt C++ 1. Qt 2. QtWebkit 3. Symbian Web Runtime

A variety of technologies available for selecting the most suitable approach

141

Qt for Mobile

Qt Applications
Qt C++

Qt Quick UI Qt C++, UI with QWidgets C++, UI with Graphics View C++ Native LAF Custom LAF Custom LAF with

easy-to-develop More native applications script-like syntax Multiple UI approaches E xtensive engine support through Q t and Q t Mobility APIs

142

Qt for Mobile

QtWebkit

WEB

Qt C++

Possibility to embed dynamic content to Q t C ++ programs E .g. create the whole UI with web technologies and show it in a QWebView widget C ollaborate between J avaS cript and C ++ R e-use existing web documents

143

Qt for Mobile

More Concretely, from iPhone/Android to Qt?


iPhone (O bjective-C ) and Android applications only work on their native platforms which are not Q t-compatibile R eusing parts of applications is basically not possible when porting to Q t
Porting requires complete code level re-implementation with Q t

Lets look briefly into a few fundamental characteristics of both platforms


C omparison to Q t C onceptual mapping of native elements to Q t

144

Qt for Mobile

iPhone Overview
Applications in iPhone are written using the Objective-C programming language Development of O bjective-C applications requires the use of Apple environment Tools in use
O bjective-C : X C ode Q t/S ymbian: Q t C reator, C arbide.c++

145

Qt for Mobile

Objective-C Application Framework


Applications for iPhone are written using O bjective-C and using the C ocoa framework
O bjective-C is actually an extension of ANS I C

The C ocoa framework consists of libraries, APIs and runtimes that form the development layer for all of Mac O S X
Applications automatically inherit the same Mac O S X LooknF eel

O bjective-C application architecture

146

Qt for Mobile

iPhone Application Features


UIKit is iPhones runtime UI framework which provides a set of UI components but also access to device services (like camera and accelometer)
S et of UI components is rather similar to Q t Homogenous LAF

O nly one foreground iPhone application can be executed at a time (excluding iPhone 4)
When user selects application icon from menu, new process launches Pressing home screen button closes the application process Applications try to imitate background execution by state saving

iPhone supports multitouch events by nature


UIEvent consists of UITouch objects (one for each finger) Q t 4.6 introduced a new G esture F ramework to provide fluent touch UI support

147

Qt for Mobile

Android Platform Overview


Android is an open and free platform for mobile phones (and mobile phones only) Based on Linux-kernel, but G oogle says it is not a Linux O S O wn windowing system Not supporting full set of standard Linux libraries, like G NU C Library
R euse of existing Linux apps or libraries difficult

148

Qt for Mobile

Android Applications Overview


Applications developed with J ava using a proprietary Dalvik VM
Device services, like touch screen and storage accessed through G oogle services API

Android does not use standard J ava APIs, such as J 2S E or J 2ME


Not compatible with J ava apps written for other platforms

Android apps do not provide one entry point (like main function) but a set of essential components
Activities, services, broadcast receivers and content providers Application process is started when any part of it is needed and J ava objects for that part are instantiated

149

Qt for Mobile

Comparing Android and Qt UI Concepts


Activity Q Widget that is a window (main widget) Q t Widgets
Activity
contains

Android Views
View structure

Different set of widgets Q t Parent/child relationship

Main widget (QWidget)


contains

Views

Dialog

Q Dialog

Child widgets (QWidget)

S imilar Layout managers E vent handling:


dispatch () on E vent() Looper::loop() Q O bject::event() Q O bject:: E vent() Q Application::exec()

150

Qt for Mobile

Porting Different Types of Mobile Apps to Qt


Applications based on web technologies or applications with embedded web content
Q tWebkit R e-use of graphics, extend engine with C ++ (S ymbian Web R untime)
WEB Qt C++ WEB

Applications with standard device UI


Q t C ++ with standard Q Widgets

Qt C++, UI with QWidgets

G ames without heavy graphics-rendering requirements


Q t Q uick

Qt Quick UI

C++

G ames with heavy, real-time graphics and/or 3D


Q t with G raphics View

C++, UI with Graphics View

151

Qt for Mobile

Porting Mobile Applications to Qt


Re-using Platform Code

152

What is Qt for Symbian? (1/2)


Applications are implemented using cross-platform Q t APIs Q t APIs are implemented using native APIs
Qt APIs Qt Application 1 Application 2 Application 3

Qt/Windows Win32 GDI Windows Kernel

Qt/Mac Carbon / Cocoa Mac HW

Qt/Symbian Eikon / OpenC Symbian

153

Qt for Mobile

What is Qt for Symbian? (2/2)


When you install Q t/S ymbian the Q t libraries are compiled as S ymbian DLLs
Q tC ore.dll, Q tG ui.dll, etc.

Y our own applications are compiled using a native compiler F rom S ymbian O S s point of view your applications are just normal S ymbian processes
But! Program code is no longer S ymbian, but cross-platform Q t code
No S ymbian coding conventions!

C an be directly re-compiled for other Q t platforms

Y ou can mix native platform code with Q t!

154

Qt for Mobile

Application Partitioning in Symbian


(Avkon in S60)
GUI GUI App UI App UI & Views & Views (EXE) (EXE)

Graphics Graphics

Your Symbian application

Engine Engine Support Support

Application Application Engine Engine (DLL) (DLL)

Base Base

155

Qt for Mobile

Porting Alternative 1/3 Hybrid UI

App UI App UI & Views & Views (EXE) (EXE)

Qt UI Qt UI (EXE) (EXE)

New UI with Qt widgets Engine left untouched Direct access to Symbian engine inside Qt UI code => Hybrid code (Qt+Symbian mixed), not cross-platform

Application Application Engine Engine (DLL) (DLL)

156

Qt for Mobile

(Bad!) Example on Hybrid UI


#include <QtGui/QLabel> #include <symbianengine.h> void MyUiClass::doSomething() { TRAPD( err, CSymbianEngine* engine = CSymbianEngine::NewL() ); if( err != KErrNone ) { CleanupStack::PushL( engine ); engine->SetSomethingL( EFalse ); QLabel* l = new QLabel( engine->GetText(), this ); CleanupStack::PopAndDestroy(); } }

Works! but only in Symbian, so not cross-platform! Problems in readability, error handling etc.

157

Qt for Mobile

Porting Alternatives 2/3 Engine Wrapper

App UI App UI & Views & Views (EXE) (EXE)

Qt UI Qt UI (EXE) (EXE)

Application Application Engine Engine (DLL) (DLL)

Qt Engine Wrapper

New UI with Qt widgets Engine left untouched Engine wrapped with a separate Qt class Engine wrapper implementation hybrid code, UI plain Qt => Clean UI code, possibility to port engine later

158

Qt for Mobile

Hiding Platform Dependency 1 Simple Wrapper


UI Code (Qt) EngineWrapper (Hybrid) CEngineClass (Symbian)

By simplest we can just wrap our existing S ymbian engine class with a hybrid class
Q t class with Q t interface and mechanisms (like S ignals&S lots) Y et, dependencies on S ymbian in class interface

UI code stays clean and plain Q t but is actually dependent on S ymbian through E ngineWrappers interface + Q uickneasy - Not very flexible, possible problems with S C /BC if going cross-platform
159

Qt for Mobile

Example Interface
#include <symbianengine.h> // Symbian dependency class EngineWrapper : public QObject { Q_OBJECT public: // Qt-style interface for engine services signals: private: CSymbianEngineClass* m_engine; // Symbian dependency };

160

Qt for Mobile

Hiding Platform Dependency 2 Private Implementation


Ui Code (Qt) EngineWrapper (Qt) EngineWrapperPrivate (Symbian) CEngineClass (Symbian)

More flexibility can be achieved by keeping even the E ngineWrappers interface as pure platform independent Q t All platform dependent functionality and data are placed inside a private class
A simple design pattern called private implementation

Q t itself has been implemented for different platforms using the same mechanism!

161

Qt for Mobile

Private Implementation in Its Simplest


// a.h class A { ... private: int x; int y; }; class A { ... private: AP* d_ptr; }; // a.h class AP; // a.cpp class AP { private: int x; int y; }; ...

Header file stays the same regardless of the contents of class AP


Binary C ompatibility for A remains despite AP being changed

162

Qt for Mobile

More on Private Implementation


If engine is ported for different platforms, only the private class needs to be replaced.
UI Code (Qt) EngineWrapper (Qt) EngineWrapperPrivate (Symbian) CEngineClass (Symbian)

EngineWrapperPrivate (maemo)

MaemoEngineClass (maemo)

As mentioned, this mechanism is also used for building cross-platform APIs (like Q t itself!)
O ne unified API Platform-specific private implementation classes

163

Qt for Mobile

More on Private Implementation


In S ymbian, using a native service quite often requires the use of Active O bjects
Asynchronous communication

The private implementation class can act as an Active O bject and transform S ymbian AO mechanism to Q t S ignals&S lots

CActive

UI Code (Qt)

EngineWrapper (Qt)

EngineWrapperPrivate (Symbian)

Some Symbian Native Server

164

Qt for Mobile

Porting Alternatives 3/3 Re-Implementation

Qt UI Qt UI (EXE) (EXE)

OR
Qt Engine Qt Engine (DLL) (DLL)

Qt UI Qt UI + + Engine Engine (EXE) (EXE)

Qt provides strong and easyto-use engine support so reimplementing the whole engine is something to also consider Mobility APIs extend Qt engine support to mobile devices

165

Qt for Mobile

Pros/Cons of Full Qt Reimplementation


+ Platform independency
All Q t platforms achievable

+ Better maintainability
Less code, clearer, only one code technology in use

- More work
- O bviously

- E fficiency in some cases


- O ne more code layer

166

Qt for Mobile

Porting Summary
iPhone & Android
No code re-use Web content/graphics can be re-used Different alternatives for re-implementation for different purposes (Q t, Q t w/ G raphics View, Q t Q uick, Q tWebkit, WR T)

S ymbian & Maemo


C ode re-use possible UI should be ported and E ngine should be wrapped

167

Qt for Mobile

Introduction to Mobile Qt UI

168

Mobile Qt UI Offering

QWidgets

NATIVE LAF

169

Qt for Mobile

Native Look-and-Feel w/ QWidgets


C ode once, look native everywhere Pretty straightforward C an customize, a bit
S tyle sheets Widget properties O wn custom widgets

C omplete customization not easy/possible


G ames, completely different kind of UIs

Q uite desktop-oriented
Missing mobile concepts, like views Not really there yet, at least in S ^3

170

Qt for Mobile

Animations & Effects


Spicing Up QWidget UIs

171

Introduction 1(2)
In Q t 4.6 a new Animation F ramework was introduced The idea is to provide an easy and scalable way of creating animated and smooth G UIs
Hides the complexity of handling timers Provides a set of pre-defined easing curves, custom curves can be provided by the developer as needed

Works by modifying the properties of the QObjects being animated

172

Qt for Mobile

Main Classes

173

Qt for Mobile

Example Animating a Button


What do you think the example below does?

QPushButton button("Animated Button"); button.show(); QPropertyAnimation animation(&button, "geometry"); animation.setDuration(10000); animation.setStartValue(QRect(0, 0, 100, 30)); animation.setKeyValueAt(0.5, QRect(250, 250, 100, 30)); animation.setEndValue(QRect(0, 0, 100, 30)); animation.start();

Demo
174

Qt for Mobile

Animation Groups 1(2)


C lasses QSequentialAnimationGroup and QParalleAnimationGroup can be used to run multiple animations in sequence or in parallel
An animation group can be used wherever a normal animation could e.g. a group within a group E nables building very complex animation sequences

175

Qt for Mobile

Animation Groups 2(2)


QPropertyAnimation* animation1 = new QPropertyAnimation(...); QPropertyAnimation* animation2 = new QPropertyAnimation(...); QPropertyAnimation* animation3 = new QPropertyAnimation(...); QPropertyAnimation* animation4 = new QPropertyAnimation(...); QParallelAnimationGroup *parallel = new QParallelAnimationGroup(); parallel->addAnimation(animation2); parallel->addAnimation(animation3); QSequentialAnimationGroup* seq = new QSequentialAnimationGroup(); seq->addAnimation(animation1); seq->addAnimation(parallel); seq->addAnimation(animation4); seq->start();

176

Qt for Mobile

Easing Curves
The Animation F W provides multiple pre-made easing curves for your convenience
R epresented by the class QEasingCurve

Typically used to control e.g. how the animation starts and/or finishes
QEasingCurve::OutBounce QEasingCurve::InOutQuad
QPropertyAnimation animation(&button, "geometry"); animation.setEasingCurve(QEasingCurve::OutBounce);

Take a look at the E asing C urves example in the Q t D emo tool


Demo
177

Qt for Mobile

Graphics Effects
G raphics effects provide an easy-to-use mechanism for adding effects on QGraphicsItems and QWidgets
QGraphicsItem::setGraphicsEffect(QGraphicsEffect*) QWidget::setGraphicsEffect(QGraphicsEffect*)

A group of standard effects are provided


S ee next slide for examples

C ustom effects can be created by the developer


S imply a matter of imlementing a virtual draw() function S ee documentation in the base class QGraphicsEffect for details and guidelines

178

Qt for Mobile

Standard Effects
QGraphicsBlurEffect QGraphicsOpacityEffect

Source Image

QGraphicsColorizeEffect

QGraphicsDropShadowEffect

179

Qt for Mobile

Applying and Animating an Effect


// Set up an effect QGraphicsOpacityEffect* effect = new QGraphicsOpacityEffect(this); effect->setOpacity(1.0); // 0.0 means fully transparent, 1.0 fully opaque // Apply to a graphics item QGraphicsPixmapItem *item = new QGraphicsPixmapItem(...); item->setGraphicsEffect(effect); // Animate the effect QPropertyAnimation* animation = new QPropertyAnimation(effect, opacity); animation->setDuration(1000); animation->setStartValue(1.0); animation->setEndValue(0.0); animation->start();

Demo
180

Qt for Mobile

Hands-On Animations!
Play around with
Animation F W G raphics E ffects

Make the two buttons change change place Make a slider follow the other, with a delay

181

Qt for Mobile

Mobile Qt UI
Graphics View

182

Mobile Qt UI Offering

QGraphicsView

CUSTOM LAF

QWidgets

NATIVE LAF

183

Qt for Mobile

Custom UI w/ QGraphicsView
Q G raphicsView is a Q Widget, designed for showing custom 2D graphics:
ra mg sto Cu ph s th e go re

If the only widget (the window itself) is a Q G raphicsView, the whole UI is then custom:

184

Qt for Mobile

Graphics View Architecture


Actually, inside a Q G raphicsView, lies an architecture of its own
S uper-duper optimized for doing everything fast and being flexible
QGraphicsView

Shows contents of one

QGraphicsScene

is a 2D container for

QGraphicsItem

185

Qt for Mobile

Working with GraphicsView


Y ou code your mice yourself! C reate a custom graphics item:
Derive from Q G raphicsItem (or some other Q G raphics* base class) Write code for painting operations with Q Painter Write code for event handling Write code for animations etc.

186

Qt for Mobile

Mobile Qt UI
QtWebKit

187

Mobile Qt UI Offering

QGraphicsView

QtWebkit

CUSTOM LAF

QWidgets

NATIVE LAF

188

Qt for Mobile

Hybrid Apps with QtWebkit


Write UI (+logic) with standard web technologies E mbed in a Q t/C ++ Application Key C ++ classes:
Q WebView Q WebPage Q WebF rame
Shows contents of

MyUi.html *.css *.js

QWebView

Qt/C++ Application

189

Qt for Mobile

Hybrid Apps w/ QtWebkit


Web technology experts can contribute easily to Q t applications Q t C ++ engine and Web UI can interact!
Logic can be written with J avaS cript as well

Port easily from an existing Web app (like an iPhone app) UI loaded dynamically (HTML/J avaS cript)
C an actually be a dynamic UI with online content!

http://wiki.forum.nokia.com/index.php/Q t_ hybrid_ applications http://wiki.forum.nokia.com/index.php/Hybrid_ Application_ G enerator

190

Qt for Mobile

Demo: Worlds Simplest Web Browser

191

Qt for Mobile

Mobile Qt UI
Qt Quick

192

Mobile Qt UI Offering

QGraphicsView

Qt Quick

QtWebkit

CUSTOM LAF

QWidgets

NATIVE LAF

193

Qt for Mobile

What is Qt Quick?
Q t User Interface C reation K it
UIs written in a J avaS cript-like language called Q ML

A high-level UI technology for easily creating attractive UIs


No C ++ skills needed, knowledge of J avaS cript helps quite a bit

Aimed at both UI designers and developers alike


E nables designers and developers to speak the same language! Both parties can be involved in iterative development simultaneously No need for separate F lash or PowerPoint UI prototypes

This is the future of UI development in Qt!


Q t Q uick was officially launched in Q t 4.7 R eleased 9/2010

194

Qt for Mobile

Demonstrations
Lets study this a bit by looking at a few examples

195

Qt for Mobile

GPU Accelerated Qt Quick in N8: Flowd Example


flowd.com

196

Qt for Mobile

Inside Flowd

QML UI QtMobility APIs QtDeclarative

Qt/C++ Engine

197

Qt for Mobile

Experiences with Serious Qt Quick Development


R eally Q uick to develop
F ast prototyping Also, great fun

BUT, Lots of things missing: No UI F W


View switching manual loading/unloading of resources portrait/landscape

No components (yet)
no styling

198

Qt for Mobile

Qt Mobility Bindings
Q t Mobility 1.1 (now in beta) includes Q ML Bindings for some parts Y ou can access mobility APIs functionality directly from Q ML At the moment the following are available to Q t Q uick:
G allery Location Multimedia S ervice F ramework Messaging

199

Qt for Mobile

Summary

200

New Features in Qt 4.7


Qt Quick, the Qt Ui C reation Kit
QML , a declarative, J S -like, language for designers and developers for creating animated and fluid User E xperience QtDeclarative, a C ++ library to integrate Q ML declarations into the Q t G raphics View QtC reator 2.0 supports Q ML editing

New networking possibilities


Bearer Management API from Q tMobility integrated to the Q tNetwork module

O verall performance improvements


E specially in Q tWebKit for faster web page rendering

201

Qt for Mobile

Things Expected Later


Q tO penG L in Q t/S ymbian
Developer version of Q t 4.7.0 containing Q tO penG L already available however, cannot be used for creating applications to be published in O vi S tore!

New multimedia functionality


Phonon will be replaced by Multimedia of Q tMobility Nearly made it to Q t 4.7 already

Q uite a bunch of new Q tMobility APIs Q t Q uick Designer (Dragndrop editor for Q ML) finalized Q t Q uick C omponents Q tWebkit constantly improved (HTML5 etc)

202

Qt for Mobile

Qt Developer Offering
Qt Quick, Qt Quick C omponents

UI
QtDeclarative QtWebkit

QtSvg

QtGUI

QtOpenGL

Engine

Qt
QtScript QtSql QtXml QtMultimedia QtCore QtXmlPatterns QtNetwork

85% of use cases **

Mobile Features Low level Native access


Native APIs

Qt Mobility APIs

S ymbian C ++
O pen C / PO S IX

Linux C /C ++ libraries

15% of use cases **

Desktop OSs

Symbian Symbian

Linux MeeGo

203

Qt for Mobile

Thank You!

tuukka.ahoniemi@ digia.com

www.digia.com
204

Qt for Mobile

You might also like