Qt Mobile Exercise Book

download Qt Mobile Exercise Book

of 12

Transcript of Qt Mobile Exercise Book

  • 7/30/2019 Qt Mobile Exercise Book

    1/12

    Qt for Mobile Development

    Workbook

    Version 2.5

  • 7/30/2019 Qt Mobile Exercise Book

    2/12

    Prerequisities

    The participants should have knowledge on C++ language with basic object orientedfeatures including classes and object, inheritance and virtual methods. Template

    principles are needed only for understanding Qts collection classes. No STL or RTTI (run-time-type-information) knowledge of standard C++ required.

    Tools and Versions

    The exercises are based on Qt 4.6.3 or newer. Nokia Qt SDK is required for using QtMobility APIs and for building and deploying applications to Symbian or Maemo handsets.

  • 7/30/2019 Qt Mobile Exercise Book

    3/12

    Exercise session 1: Basic Qt GUI application and tools

    ObjectivesVerifying the installation and environment

    To write the very first Qt applicationUnderstanding the basic concepts of Qt applicationsIntroducing Qt Creator IDE and Nokia Qt SDK

    a) Open the Qt Creator ofNokia Qt SDKand a new empty Qt 4 project.

    b) To your project, add a new C++ source file (e.g. main.cpp) and write a basicHelloWorld like application (refer to the lecture slides).

    c) Build and run the application on different targets e.g. desktop (Linux or Windows),mobile simulator and if available, on MeeGo SDK environment also.

    d) Try different fonts and font colors to present text in your label component. If youknow how to write HTML, you can also modify the component text by writing HTMLcode inside the text string or the label.

    e) Modify the application so that there is a QPushButton instead of QLabel. Addfunctionality where the application exits when the user presses the button.

    f) Get familiar with the help system of Qt Creator. How can you easily open the apidocumentation of a specific class? In which situations QPushButton instances sendsignals? Does the QPushButton class define any slots?

  • 7/30/2019 Qt Mobile Exercise Book

    4/12

    Exercise session 2: Creating a Trip Cost Calculator App GUI

    Objectives

    Hand-coding a GUI application

    Getting familiar with basic widgets and layout managers

    In this exercise we implement an application, which calculates the fuel costs of a cartrip. The inputs are fuel consumption (liters/100kms), fuel cost per liter and tripdistance. The basic application GUI could consist of e.g. QLabels, QLineEdits and aQPushButton but use here some other input widgets like sliders or dial components.Implement the GUI your own main widget class deriving from QWidget. In the mainmethod you just initialize the application and create an instance of your widget.

    a) Create an empty Qt4 project for your application by using Qt Creator (as in exercise1). Name your project e.g. as TripCostCalculator

    b) Add a new class named TripCostCalculator by using Qt C++ Class Wizard (can be foundfrom File->Add New).

    c) Implement the GUI in the widget class constructor by first creating a layout e.g.QVBoxLayout and then the widgets itself one by one. Remember to add your widgetclass as a parent for the layout and then add the child widgets (QLabel, QLineEditetc..) to the widget. Remember the proper memory management!

    d) Create a main.cpp file where you create QApplication instance, create and show yourwidget and execute the application. Build and run the GUI.

  • 7/30/2019 Qt Mobile Exercise Book

    5/12

    Exercise session 3: Adding Signals and Slots

    Objectives

    The main objective of the exercise is to learn Qts signal-slot mechanism in practice. Wecontinue the previous exercise by implementing functionality to the application. We adda new slot, which we connect to the Calculate buttons clicked() signal.

    a) In your main widget, add a slot calculateTripCost(). Remember to add this underpublic/private slots section of the widget class header file. Implement the slot as anormal C++ method in .cpp file. The slot should just take the values the user hasentered to QLineEdit components and then convert them to numbers (QString classhas the methods for that).

    Texts of QLineEdit components can be accessed by using method text(). The method

    returns the as a QString.

    b) In the widgets constructor, connect the signal emitted by QPushButton to your slotwhere you calculate the trip cost and show the result in the result label.

    c) Build and run the applicationd) Try debugging the application by setting breakpoints and running the code line by line

    exploring the variables.

    Optional extra exercise if you have time: Write a signal to your widget and slot for the

    signal. Emit the signal at some point in the code. Test your signal-slot implementationwith no parameters and by passing some data across the objects (e.g. an integer).

  • 7/30/2019 Qt Mobile Exercise Book

    6/12

    Exercise session 4: Creating GUIs by using Qt Designer

    Objectives

    In this exercise we learn how to make use of Qt Designer tool in creating GUIs in a quick

    and visual way. We also get familiar with basic features and functionality of Qt Creatorincluding the signal-slot editor and auto-connected slots.

    a) Open Nokia Qt SDK and create a new Qt 4 GUI application namedBodyMassIndex. This will now create files for basic Qt GUI project and open a QtDesigner form.

    b) With Qt UI Designer, implement an application which counts the Body Mass Indexand shows the result to the user. Create a new project and choose Qt GUIApplication. Select the input and display widgets from UI Designer to create a nice

    GUI for this.

    c) With signal/slot editor of the Qt Designer, connect signals and slots betweensliders and lcd numbers.

    d) Implement the calculation functionality for the application. The body mass indexis calculated by the following formula:

    BMI = weight (kg) / (height(meters) x height(meters))

  • 7/30/2019 Qt Mobile Exercise Book

    7/12

    Exercise session 5: Main Windows, Menus and Actions

    Objectives

    If we want to implement menus and actions in our application, we can just derive our

    main GUI class from QMainWindow instead of QWidget. Menus and actions can then becreated either by simply hand-coding them (examples in slides) or by using Qt Designer.Hand-coding can be done like as follows:

    QMenu* menu = menuBar()->addMenu(File);QAction* openAction = menu->addAction(Open);connect( openAction, SIGNAL(triggered()), this, SLOT(openFile()) );

    QAction represents a menu item in menus. QAction sends signal triggered(), whenselected by the user.

    a) Now create a new Qt GUI Application project named MyAnimation. SelectQMainWindow to be the base class for your application.

    b) To your project, add a new Qt C++ class AnimationWidget inheriting fromQWidget.

    c) In your QMainWindow class, add an instance of your widget. Create an instance ofyour animation widget in the constructor. After creating, the must also be set as acentral widget for the main window.

  • 7/30/2019 Qt Mobile Exercise Book

    8/12

    //Include the header of your widget class#include AnimationWidget.h//In the class declaration of your main window classprivate:

    AnimationWidget*animationWidget;};

    // In the constructor of your main window class you create the widget and// set it to be the central widget of this windowanimationWidget=newAnimationWidget(this);setCentralWidget(animationWidget);

    d) In your main window constructor, implement a menu with the following actions:Start (starts the animation)Stop (stops the animation)

    Quit (quits the application)

    e) Implement the Quit action for the application. For the Quit functionality, add amessage dialog to ask the user Exit application? with options Yes and No.

  • 7/30/2019 Qt Mobile Exercise Book

    9/12

    Exercise session 6: Painting and event handling

    ObjectivesTo practice 2D drawing on widgets

    To practice the use of timer services of QObjects

    To implement event handling: timers key and mouse events.

    Here we continue the previous exercise.

    a) Implementing paint event. Add method void paintEvent(QPaintEvent*event)to your animation widget. This is a virtual method from QWidget baseclass and is used for painting the widget itself. The QWidget implementation forthis method does not draw anything. Implement the method so that it draws thebackground with some color and an ellipse on it.

    b) To your animation widget, add a private member of type QPoint, which describesthe location for an ellipse to be moved on the screen. In paintEvent method, drawa green ellipse on the screen located by the QPoint variable.

    QPoint ellipseLocation;

    c) Adding timer events: To your widget, implement a slot, where you start a timerwith 50 ms interval. Start the timer when the user selects Start from the

    options menu. Implement timerEvent(QTimerEvent *event) method so that

    it updates the ellipseLocation QPoint and invokes update() asking the windowmanager to redraw.

    d) Starting the animation from the menu: By using timers, implement an animationwhere the ellipse moves forward and backward on the screen. Start the timerwhen the user selects Animate from the menu and stop the timer when the userselects Stop from the menu.

    e) Mouse event handling :ImplementmouseClickEvent(QMouseEvent *event)so that when the user clicks or touches the canvas, the click coordinates becomethe new location of the ellipse.

    f) Key event handling : Implement keyEvent(QKeyEvent *event) method sothat it handles the arrow key event. The direction of the ellipse is changedaccordingly.

    g) Optional (time permitting): To your project, add a Qt resource file and import animage to your application. Draw it on the screen instead of the ellipse.

  • 7/30/2019 Qt Mobile Exercise Book

    10/12

    Exercise session 7: WebKit Implementing a simple web browser byusing QWebKit.

    With Qt Designer, implement a simple web browser by using QWebView component. Add

    also QLineEdit component for the user for inputting an URL and 3 buttons Go, Reloadand Back with corresponding functionalities.

    Remember to add WebKit module to your .pro file for linking.

    QT += webkit

    If you have network connectivity, deploy and try it out on a mobile phone.

  • 7/30/2019 Qt Mobile Exercise Book

    11/12

    Exercise session 8: Using Qt Mobility APIs

    Now we take the new Qt Mobility APIs into use. However, you should install them to yourdevice too in order to test your apps there. Many of the mobility features can also betested with Qt Simulator.

    Open the Qt Mobility Documentation web page and from there Quickstart Guide to getthe latest info on what you need to add to your project. The key points here:

    #include//(1)#includeQTM_USE_NAMESPACE//(2)// In your class then..QSystemDeviceInfodeviceInfo;// Then check the API documentation for further information

    // on how to utilize the API

    a) Implement a simple Mobile Application, which shows the current battery levelpercentage on a QLcdDisplay component. The UI consists of a single QWidget withQLcdDisplay instance. The battery level API and signals related to it can be foundfrom System Info Mobility APIs. Test the application on the Mobile Simulator.

    Note! You have to set the build target to be the Simulator, Symbian or Maemotarget device in order to get this built).

    b) Test the application with different battery states, battery low states by using themobile simulator application.

    c) If you have a Maemo/MeeGo or a Symbian handset available, deploy and test theapplication on a target device. Follow the rules you can find from behind the linkon the Qt Creators Welcome view (Nokia Qt SDK).

  • 7/30/2019 Qt Mobile Exercise Book

    12/12

    Mobility API Workshop: Where am I? application featuringLocation, Google Maps, SMS Messaging and Phonebook.

    For multiple views, you can use QStackedWidget component, which can contain multiple

    QWidgets of which one can be displayed at a time. This is a way of implementing viewbased applications.

    QWidget *firstPageWidget = new QWidget;

    QWidget *secondPageWidget = new QWidget;

    QWidget *thirdPageWidget = new QWidget;

    QStackedWidget *stackedWidget = new QStackedWidget;

    stackedWidget->addWidget(firstPageWidget);

    stackedWidget->addWidget(secondPageWidget);

    stackedWidget->addWidget(thirdPageWidget);

    // Selecting the current widget

    stackedWidget->setCurrentIndex(0);

    // Or

    stackedWidget->setCurrentWidget( firstPageWidget );

    The quickest way to implement multiple views with QStackedWidget is of course using QtDesigner tool.

    Implement an application, which uses the Location API to determine the current GPSlocation (latitude and longitude). The location can then be shown on Google Maps andalso sent to the specified phone number as an SMS message. Implement the applicationUI views with Qt Designer by using QStackedWidget component.

    View1 Location/Google Maps View: When the application gets the location data, itopens Google Maps with the current location by using QWebView (see Google Maps API forhow to set the proper URL.

    View2: SMS Editor View: This view is opened when the user selects to send his/herlocation via SMS.

    View3: Contacts view (optional, time permitting).Add a button Contacts to the SMSeditor view. The button opens this view to display the contact book contacts, where theuser can select the recipient. After confirming, the SMS editor view is opened and theselected contacts phone number is displayed on the recipient field.

    Optional (time permitting): Open the previously created animated ball exercise andchange the implementation so that the ball can be directed with mobile phone sensors.Use Qt Mobility Sensor API to do the task.