Showing posts with label Qt Quick. Show all posts
Showing posts with label Qt Quick. Show all posts

Saturday, December 27, 2014

Showing Remote Image using ImageView in BB10 Cascades

While working on my BB10 App update, I required to show Remote Image using ImageView BB10 cascades API. ImageView or Image component by default does not support loading image from URL on internet. I implemented a custom component which serve the purpose and also easily integrated with ImageView.

Following is implementation for the same, I hope it will be useful to someone.

Let's start by showing how my custom component works. Following code shows how to use ImageDownloader custom component along with ImageView to display Grid of images from internet. Data Model contains two kind of URL, url for low resolution image and url for high resolution image.
import my.library 1.0

ListView {
  id: listView
  
  layout: GridListLayout {}
  dataModel: model;
  
  listItemComponents: [
      ListItemComponent {                        
          ImageView {
              id: imgView
              imageSource: "default_image.jpg"  
                                        
              attachedObjects: [
                  ImageDownloader {
                      id: imageLoader
                      url: ListItemData.mediumImage
                      onImageChanged: {                 
                          if (imageLoader.isVaid) {
                              imgView.image = imageLoader.image
                          }
                      }
                  }
              ]
          }
      }
  ]
}
ImageDownloader component is available in QML because we imported "my.library". We can make any C++ code available to QML by registering it to QML System, folloiwing snippet shows how we can register C++ component to QML system.

#include "ImageDownloader.h"

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

 qmlRegisterType<ImageDownloader>("my.library",1, 0, "ImageDownloader");

 QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(&app);

 AbstractPane *root = qml->createRootObject();
 app.setScene(root);

 return Application::exec();
}
Now that custom component is ready to be used with QML, let's see how its implemented. Below if header file for ImageDownloader class. We are defining few properties like url, image and isValid. By setting "url" we can initiate download of image, when "image" download is finished downloaded image can be accessed by using "image" property. We can check if image is valid or not by checking "isValid" property. we are also defining few signal like "urlChanged" and "imageChanged", which are emited when url is changed or image is downloaded. And we are using QNetworkAccessManager to download image from internet.
#ifndef IMAGEDOWNLOADER_H_
#define IMAGEDOWNLOADER_H_

#include 
#include 

class QNetworkAccessManager;

class ImageDownloader: public QObject
{
    Q_OBJECT
    Q_PROPERTY(QVariant image READ image NOTIFY imageChanged)
    Q_PROPERTY(QString url READ url WRITE setUrl NOTIFY urlChanged)
    Q_PROPERTY(bool isVaid READ isValid CONSTANT);
public:
    ImageDownloader( QObject* parent = 0);
    virtual ~ImageDownloader();

signals:
    void urlChanged();
    void imageChanged();

private slots:
    QString url() const;
    void setUrl( const QString& url);

    QVariant image() const;
    bool isValid() const;

    void startDownload();
    void onReplyFinished();

private:
    QNetworkAccessManager mNetManager;
    QString mImageUrl;
    bb::cascades::Image mImage;
    bool mIsValid;
};

#endif /* IMAGEDOWNLOADER_H_ */
Implementation is also quite simple, let's see how its implemented. On URL change, we are initiating the image download using QNetworkAccessManager. When download is finished, we are reading image data in to buffer and creating Image using BB10 Image API.
#include "ImageDownloader.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

ImageDownloader::ImageDownloader(QObject* parent):
    QObject(parent), mIsValid(false) {}

ImageDownloader::~ImageDownloader() {}

QString ImageDownloader::url() const {
    return mImageUrl;
}

void ImageDownloader::setUrl( const QString& url)
{
    if(url != mImageUrl) {
        mImageUrl = url;
        mIsValid = false;
        mImage = bb::cascades::Image();
        emit urlChanged();
        emit imageChanged();
        startDownload();
    }
}

QVariant ImageDownloader::image() const {
    return QVariant::fromValue(mImage);
}

bool ImageDownloader::isValid() const {
    return mIsValid;
}

void ImageDownloader::startDownload() {
    QNetworkRequest request(mImageUrl);
    QNetworkReply* reply = mNetManager.get(request);
    connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished()));
}

void ImageDownloader::onReplyFinished() {
    QNetworkReply* reply = qobject_cast(sender());
    QString response;
    if (reply) {
        if (reply->error() == QNetworkReply::NoError) {
            const int available = reply->bytesAvailable();
            if (available > 0) {
                const QByteArray data(reply->readAll());
                mImage = bb::cascades::Image(data);
                mIsValid = true;
                emit imageChanged();
            }
        }
        reply->deleteLater();
    }
}
That's all we have to do to do display remote image in BB10, hope you liked it.

Sunday, November 23, 2014

Your Shot Ubuntu Touch Scope

You might have heard about Ubuntu Touch, and one of unique feature of Ubuntu Touch is Scope. Recently they also announced Ubuntu Touch Scope competition. This got me interested, I wanted to learn about Scope development, so I thought to take part as well in the competition.

You can get more information about competition here.

Recently I discovered Your Shot photo community, I like pictures uploaded there and I visit site every day to checkout newly updated photos, so I thought it is good candidate for Scope development and I decided to write score for Your Shot photo community.

Your Shot has nice Jason based web API and I was able to create scope quite easily using Ubuntu Touch socpe's Jason template. In fact I was able to get decent working scope in few hours using template. Documentation is also quite good and rich with API Reference, Guide and Tutorials.

Here is demo for the same running on my desktop.


And Few snapshot.





It looks like now I am ready to write more complex Scope but may be later.

Thursday, October 30, 2014

Creating dynamic QML object asynchronously

We can create QML object dynamically by using createComponent and createObject API.

Like follow,
var component = Qt.createComponent("Button.qml");
if (component.status == Component.Ready)
    component.createObject(parent, {"x": 100, "y": 100});
You can find more information regarding same here.

Latest Qt release added new API named incubateObject. This allows object to be created in asynchronously. You can find more information about this API here.

Following code I written for Ubuntu touch calendar application, which uses the same. Here thing to remember is that incubateObject returns the incubator and not created object itself. You need to get object from incubator by incubator.object call.
var incubator = delegate.incubateObject(bubbleOverLay);
if (incubator.status !== Component.Ready) {
    incubator.onStatusChanged = function(status) {
        if (status === Component.Ready) {
            incubator.object.objectName = children.length;
            assignBubbleProperties( incubator.object, event);
        }
    }
} else {
    incubator.object.objectName = children.length;
    assignBubbleProperties(incubator.object, event);
}

Saturday, June 7, 2014

Geting Call notification from Cascades QML code in BB10

I was updating my Audiobook Reader application. I wanted to listen to our going or incoming call and pause book accordingly.

BB10 provides nice API to control call and listen to it.

This post will show how we can listen to call from Cascades QML code. First we need to ask for access_phone and control_phone permission in our bar descriptor file.
    <permission>access_phone</permission>
    <permission>control_phone</permission>
Now we need to link system lib to our app.
LIBS += -lbbsystem 
Once this is done, we need to register Phone type to QML system so we can access it from QML.

#include <bb/system/phone/Phone>
...
using namespace bb::system;

int main(int argc, char **argv) {
    qmlRegisterType("bb.system.phone", 1, 0, "Phone");
    ...
}
Now we are ready to use Phone API from QML side. Following is how QML code will look like. In code we are creating Phone object. On any call related event callUpdated signal will be called. So we are handling that signal in onCallUpdated event. Please note that we can not access Call's properties with QML, as its not derived from QObject, so if you need to access properties of Call then you need to forward call to C++ and handle it there.

import bb.system 1.0
import bb.system.phone 1.0

Page {
    attachedObjects: [
        Phone {
            id: phone
            onCallUpdated: {
                console.log(" ############## Phone::onCallUpdated ") ; 
                //do the needful
            }
        }
    ]
}
Thant's it. Hope it will be helpful.

Sunday, April 13, 2014

Creating Custom Swipe handler in QML

I was often request for sample that shows how custom swipe handler can be created in QML. In this post I will show how same can be achieved.

Please note that code is just prototype level code and is not tested well with actual use. It has also lots of hard coded value that assume certain size of application.

But, you should be able to change those according to your use and can try sample with your app.

This sample implement three QML views and you can swipe on that to change view from one to next. This code also implement some parallax effect on view and view transition animation. In addition to swipe you can also change view using keyboard Left/Right arrow key. Following is demo for the sample app.



So let's start with code.

Following code is from SwipeHandler.qml, it extends MouseArea and try to detect swipe based on mouse's x position change. Swipe can be generated by two way, by flicking on view or dragging it.
Flick is detected, if there is large change in mouse x position in less time. In case of drag, if mouse travel certain distance then code consider it as a swipe.

import QtQuick 2.0

MouseArea{
    id: root

    property int oldX: mouseX;
    property int swipeOffset: 100;
    property int originX:mouseX;

    property var gestureStartTime;
    property bool gestureStarted: false;

    signal swipeEnded(var diff);
    signal swipeContinues(var diff);

    anchors.fill: parent

    onReleased: {
        if( gestureStarted ) {
            //swipe canceled
            root.swipeEnded(0);
            resetGesture();
        }
        //else swipe is already ended
    }

    onPressed: {
        gestureStarted =  true;
        gestureStartTime = new Date();
    }

    onMouseXChanged: {
        if( mouseX < parent.x
        || mouseX > parent.width || gestureStarted == false )
            return;

        if( originX == 0 ) {
            originX = mouseX; oldX = mouseX;
            return;
        }

        var diff = (oldX - mouseX);
        if(handleFlick(diff)){
            return;
        }

        if( haldleDrag(mouseX, diff)){
            return;
        }

        oldX = mouseX;
        root.swipeContinues(diff);
    }

    function resetGesture() {
        originX = 0; oldX = 0;
        gestureStarted =  false;
    }

    function haldleDrag(xPos,xPosDiff){
        if(xPosDiff < 0) {
            if( Math.abs(originX-xPos)  > swipeOffset ){
                root.swipeEnded(xPosDiff);
                resetGesture();
                return true;
            }
        } else {
            if( Math.abs(originX-xPos) >  swipeOffset ){
                root.swipeEnded(xPosDiff);
                resetGesture();
                return true;
            }
        }
        return false;
    }

    function handleFlick(xPosDiff){
        var now = new Date();
        var timeDiff = now - gestureStartTime;

        //high velocity and large diff between start end point
        if(timeDiff < 40 && Math.abs(xPosDiff) > 10 ){
            if(xPosDiff < 0) {
                root.swipeEnded(xPosDiff);
                resetGesture();
                return true;
            } else {
                root.swipeEnded(xPosDiff);
                resetGesture();
                return true;
            }
        }
        return false;
    }
}
So, this was SwipeHandler which can detect if swipe is generated or not. To demonstrate its use, I created a small View Management component, that create's three views. On swipe, view changes form one to another base on direction of swipe movement. Here is code for the same.
import QtQuick 2.0

Rectangle {
    id: root
    width: 200
    height: 300

    property var delegate: comp;

    property var centralView;
    property var nextView;
    property var prevView;

    focus: true

    Component.onCompleted: {
        var colors = ["red","blue","green"];
        var objs = [];
        for(var i =0; i < 3; ++i){
            var obj = comp.createObject(root);
            obj.text = i+1;
            obj.color = colors[i];
            objs.push(obj);
        }

        centralView = objs[0]
        nextView = objs[1]
        prevView = objs[2]

        setViewPos();
    }

    function setViewPos(oldX){
        centralView.animate(50,0);
        nextView.animate(50,root.width);
        prevView.animate(50,-root.width);

        centralView.z = 1;
        nextView.z = 0;
        prevView.z = 0;
    }

    Keys.onRightPressed: {
        var tempView = centralView;
        centralView = prevView;
        prevView = nextView;
        nextView = tempView;

        centralView.animate(150,0);
        nextView.animate(150,root.width);
        prevView.x = -width
    }

    Keys.onLeftPressed: {
        var tempView = centralView;
        centralView = nextView;
        nextView = prevView;
        prevView = tempView;

        centralView.animate(150,0);
        prevView.animate(150,-root.width);
        nextView.x = width
    }

    SwipeArea{
        onSwipeEnded: {
            if(diff === 0) {
                root.setViewPos();
                return;
            }

            var tempView = centralView;
            if(diff < 0) {
                centralView = prevView;
                prevView = nextView;
                nextView = tempView;
            } else {
                centralView = nextView;
                nextView = prevView;
                prevView = tempView;
            }
            root.setViewPos();
        }

        onSwipeContinues: {
            centralView.x = centralView.x - diff;
            if(diff < 0) {
                prevView.x = prevView.x  + Math.abs(diff*1.6);
                prevView.z = 1
                centralView.z = 0;
            } else {
                nextView.x = nextView.x - Math.abs(diff*1.6) ;
                nextView.z = 1
                centralView.z = 0;
            }
        }
    }

    Component{
        id: comp
        Rectangle{
            id: rect
            property alias text: label.text

            width: parent.width; height: parent.height
            Text{
                id: label; anchors.centerIn: parent
            }

            function animate(duration, to){
                anim.to = to; anim.duration = duration
                anim.running = true
            }

            PropertyAnimation{
                id: anim; target:rect; property: "x";duration: 50
            }
        }
    }
}

Friday, August 30, 2013

Ubuntu Touch Calendar prototype for new design


Lately I am working on Ubuntu Touch's Calendar core app. Recently I tried to create a prototype for calendar to show how new design looks for the app.

Here if demo on youtube.



And following are few snaps from prototype.






Saturday, June 8, 2013

Using QML Camera and passing image to C++ code

I tried to compile one my application with Qt5. Application was using QML camera and sharing image to C++ code for further processing.

Following is sample code, it works with Qt5 and Qt Multimedia 5.

Lets start with ImageProcessor class, the C++ class which is called from QML to further image processing.

Following is header file for ImageProcessor class, it declares processImage() slot which can be invoked from QML code.
#ifndef IMAGEPROCESSOR_H
#define IMAGEPROCESSOR_H

#include <QObject>

class ImageProcessor : public QObject
{
    Q_OBJECT
public:
    explicit ImageProcessor(QObject *parent = 0);
 
public slots:
    void processImage( const QString& image);   
};
#endif // IMAGEPROCESSOR_H
Following is cpp file for ImageProcessor class. processImage() function retrieves Image from camera image provider. Once we have valid image, we can process it further.
#include "imageprocessor.h"
#include <QtQml/QmlEngine>
#include <QtQml/QmlContext>
#include <QtQuick/QQuickImageProvider>
#include <QDebug>

ImageProcessor::ImageProcessor(QObject *parent)
    : QObject(parent)
{}

void ImageProcessor::processImage( const QString& path)
{
    QUrl imageUrl(path);
    QQmlEngine* engine = QQmlEngine::contextForObject(this)->engine();
    QQmlImageProviderBase* imageProviderBase = engine->imageProvider(
     imageUrl.host());
    QQuickImageProvider* imageProvider = static_cast<QQuickImageProvider>
     (imageProviderBase);
    
    QSize imageSize;
    QString imageId = imageUrl.path().remove(0,1);
    QImage image = imageProvider->requestImage(imageId, &imageSize, imageSize);
    if( !image.isNull()) {
        //process image
    }
}
Now we need to register ImageProcessor class with QML. so that we can use it from QML code. This can be done by using qmlRegisterType global function.
#include  <QtGui/QGuiApplication>
#include  <QQmlEngine>
#include  <QQmlComponent>
#include  <QtQuick/QQuickView>

#include "imageprocessor.h"

int main(int argc, char *argv[])
{
    qmlRegisterType<ImageProcessor>("ImageProcessor", 1, 0, "ImageProcessor");

    QGuiApplication app(argc, argv);

    QQuickView view;

    QObject::connect(view.engine(),SIGNAL(quit()),&app,SLOT(quit()));    
    view.setSource(QUrl::fromLocalFile("qml/main.qml"));
    view.show();

    return app.exec();
}
That's all from C++ side, QML code is event easier. Following how you can use ImageProcess class from QML code.
import QtQuick 2.0
import QtMultimedia 5.0
import ImageProcessor 1.0

Rectangle {
    width: 360
    height: 360

    //shows live preview from camera
    VideoOutput {
        source: camera
        anchors.fill: parent
        focus : visible
    }

    //shows captured image
    Image {
        id: photoPreview
        anchors.fill: parent
        fillMode: Image.PreserveAspectFit
    }

    Camera {
        id: camera
        imageProcessing.whiteBalanceMode: CameraImageProcessing.WhiteBalanceFlash
        captureMode: Camera.CaptureStillImage

        exposure {
            exposureCompensation: -1.0
            exposureMode: Camera.ExposurePortrait
        }

        flash.mode: Camera.FlashRedEyeReduction

        imageCapture {
            onImageCaptured: {
                photoPreview.source = preview
                imageProcessor.processImage(preview);
            }
        }
    }

    MouseArea{
        anchors.fill: parent
        onClicked: {
            camera.imageCapture.capture();
        }
    }

    //image processor for further image processing
    ImageProcessor{
        id: imageProcessor
    }
}

Wednesday, April 17, 2013

Creating QML ListView with Search support

In last post I posted initial implementation for my Audiobook Reader app for Ubuntu-Touch, I was able to add some more features to it then after. I added support for Adding and removing custom bookmark and play the custom bookmark.

I also added support for searching the books by title in book list view. Similar to email application in Nokia N9. In this post I will show how similar feature can be implemented in QML application.

In my implementation if you pull down the book list, then it will show the search box. You can type in that search box and it will try to show books that matches that typed text. If you don't type for some time, search box will gets disappear.

Here is demo,



Following is my code. First I created TextField where user can type search text. If user type some text then I am applying the filter to my list's data model using typed text and also resetting the timer, which is responsible in hiding the search field.
    ....
    TextField{
        id: searchField
        width: parent.width
        visible: false

        onTextChanged: {
            timer.restart();
            if(text.length > 0 ) {
                model.applyFilter(text);
            } else {
                model.reload();
            }
        }

        onVisibleChanged: {
            if( visible) focus = true
        }

        Behavior on visible {
            NumberAnimation{ duration: 200 }
        }
    }
Following is my list view, Here I am setting its y property based on visibility of search field. Data model implements method for showing filtered data or all the data. Other important function is onContentYChanged, this function makes search field visible if user pull down the book list view.

    ListView {
        id:listView
        clip: true
        width: parent.width
        height: parent.height
        y: searchField.visible ? searchField.height : 0

        Behavior on y {
            NumberAnimation{ duration: 200 }
        }

        model: ListModel {
            id: model
            Component.onCompleted: {
                reload();
            }

            function reload() {
                var bookList = DB.getAllBooks();
                model.clear();
                for( var i=0; i < bookList.length ; ++i ) {
                    model.append(bookList[i]);
                }
            }

            function applyFilter(bookName) {
                var bookList = DB.getBooksByName(bookName);
                model.clear();
                for( var i=0; i < bookList.length ; ++i ) {
                    model.append(bookList[i]);
                }
            }
        }

        delegate: listDelegate

        onContentYChanged: {
            if( contentY < -100 ) {
                searchField.visible = true;
                timer.running = true;
            }
        }
    }

Lastly the timer, which is responsible for hiding the search field if user don't type anything for certain duration.
    Timer{
        id: timer; running: false; interval: 7000; repeat: false
        onTriggered: {
            searchField.visible = false;
        }
    }
That's all needed to add search support to QML ListView.

Thursday, April 4, 2013

Accessing Amazon AWS service from QML/Javascript

Sometime back I published a post that shows how to access Amazon Web Service using Qt. You can find original post here. Now that trend is to code everything from QML and Javascript ( at-least Ubuntu Touch is following that path to make it as device independent as possible), I tired to access AWS service from using pure QML and Javascript.

I required to use external Crypto library for HMACSHA1 algorithm but everything else can easily be done with pure QML/Javascript.

Following is code i used for downloading Book cover image from Amazon AWS.

First all to communicate with AWS you required to have AWS access key id and Secret Access key. You can get it from here. I am also importing the Crypto library, for using HmacSHA1 implementation. I am using crypto-js Library. You can download required the same from here.

.import "JSLib/rollups/hmac-sha1.js" as Crypto

//key and password, required to sign the request using HMACSHA1
var AWS_KEY = "KEY";
var AWS_PASS = "PASSWORD";
var END_POINT = "http://ecs.amazonaws.com/onca/xml";
var AWS_TAG = "TAG"

Now we have required information, we can are ready to create request. In following code, I am putting all required parameter in a map and then using it to create signature and URL. We also need to encode parameter, I am using encodeURIComponent for encoding required parameter.
function downloadCover( author,bookName,callback) {

    var queryItems = {};
    queryItems["AWSAccessKeyId"] = AWS_KEY;
    queryItems["AssociateTag"] = AWS_TAG;
    queryItems["Author"] = encodeURIComponent(author);
    queryItems["Keywords"] = encodeURIComponent(bookName);
    queryItems["Operation"] = "ItemSearch";
    queryItems["ResponseGroup"] = "Images";       
    queryItems["SearchIndex"] = "Books";
    queryItems["Service"] = "AWSECommerceService";
    queryItems["SignatureMethod"] = "HmacSHA1";
    queryItems["Timestamp"] = encodeURIComponent( new Date().toISOString());
    queryItems["Signature"] = createSignature(queryItems);


    var downloadUrl = createUrl(queryItems);
    sendNetworkRequest(downloadUrl,callback);
}
Following is code for creating signature. Creating signature is the only tricky part to make code works as expected. I am using HmacSHA1 from Crypto-JS lib. This function return WordArray object, which can be converted to HEX string, binary string or base64. Once we have HmacSHA1 hash of request, we need to convert it to Base64. I was not able to use base64 function from Crypto-JS library due to some error. I decided to copy base64 function from library directly to my js file and use it. Then finally we need to encode this base64 output, which we can be used as signature while sending request.
function createSignature(queryItems) {
    var strToSign = "GET\n";
    strToSign += "ecs.amazonaws.com\n";
    strToSign += "/onca/xml\n"

    for( var prop in queryItems ) {
        if( prop === "Signature") {
            continue;
        }

        strToSign += ( prop+"="+ queryItems[prop]);
        strToSign += "&"
    }
    //removing last &
    strToSign = strToSign.slice(0,strToSign.length-1)


    var signature = Crypto.CryptoJS.HmacSHA1(strToSign, AWS_PASS);
    signature = base64(signature);

    return encodeURIComponent(signature);
}

Now we are almost done, all we need to do is to use created signature and make HTTP request. Following code shows how. There is nothing new here. I am creating complete URL from all required parameter and making request using this URL by XMLHttpRequest object.

function createUrl(queryItems )
{
    var url = END_POINT+"?";

    for( var prop in queryItems ) {
        url += ( prop+"="+ queryItems[prop]);
        url += "&"
    }
    //removing last &
    url = url.slice(0,url.length-1);
    return url;
}

function sendNetworkRequest(url,callback) {
    var http = new XMLHttpRequest();
    http.onreadystatechange = function() {
        if (http.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
            console.log("Headers -->");
            console.log(http.getAllResponseHeaders ());
            console.log("Last modified -->");
            console.log(http.getResponseHeader ("Last-Modified"));

        } else if (http.readyState === XMLHttpRequest.DONE) {
            console.log(http.responseText);
            callback(http.responseText);
        }
    }

    http.open("GET", url);
    http.send();
}

Friday, March 1, 2013

Using LocalStorage API from javascipt in QML application

Recently I needed to create database from QML application on which I am working. I wanted to separate database related code from QML and created javascript file to handle database related work. I had to struggle a little to make storage API work from javascript, below are my findings.

As you might already know to use sqllite database in QML you will need to import LocalStorage API.
import QtQuick.LocalStorage 2.0 as Sql
This will work for QML but if you want to use it from javascript then you will need to use following syntax.
.import QtQuick.LocalStorage 2.0 as Sql
Now you should be able to use LocalStorage API in javascript. LocalStorage related API can be accessed by using LocalStorage object and we imported LocalStorage module as Sql, we will need to use access LocalStorage object from Sql scope. Like below.
var db = 
   Sql.LocalStorage.openDatabaseSync("TestDB", "1.0", "Description", 100000);
Now you can use this db object to create table and select values from it just like you do in QML. Following is sample example.
function getDatabase() {
     var db = 
     Sql.LocalStorage.openDatabaseSync("TestDB", "1.0", "Description", 100000);

     //create table
     db.transaction(
        function(tx) {    
var query="CREATE TABLE IF NOT EXISTS TEST(Id INTEGER PRIMARY KEY, Title TEXT)";                   
            tx.executeSql(query);
      });

     return db;
}

function printValues() {

    var db = getDatabase();
    db.transaction( function(tx) {
        var rs = tx.executeSql("SELECT * FROM TEST");
        for(var i = 0; i < rs.rows.length; i++) {
            var dbItem = rs.rows.item(i);
            console.log("ID:"+ dbItem.Id + ", TITLE:"+dbItem.Title);
        }
    });
}

Friday, April 27, 2012

Upload photo on facebook using Qt

Some time back I wrote blog post about how to Post message on facebook wall, Here is link.

This post I will show how to upload a photo from local machine to facebook. On facebook photo can be uploaded to application's album or existing album created by user or application.

Where photo will be uploaded is decided by URL used during http requst.

https://graph.facebook.com/USER_ID/photos will upload photo to application's album, https://graph.facebook.com/ALBUM_ID/photos will upload photo to specific album indicated by ALBUM_ID.

My code describe method to upload photo to application's album. You can visit this post to know how to login and how to post message on facebook wall.

This post describe process how to upload photo using php, I tried to convert that code to Qt code. As code shows that photo is uploaded using multipart/form-data method, we need to create post request with multipart/form-data method.

Following code describe the process.

void FacebookHelper::uploadPicture(const QString& picLocation, 
    const QString& comment) {
    if( !isAuthorized() ) {
        qDebug() << "Please login first...";
        emit messageStatus(1,"Please login first...");
        return;
    }

   // Show photo upload form to user and post to the Graph URL
    QString uploadUrl = "https://graph.facebook.com/me/photos?access_token="
       + mAccessToken;

    QFileInfo fileInfo(picLocation);
    QFile file(picLocation);
    if (!file.open(QIODevice::ReadWrite)) {
        qDebug() << "Can not open file:" << picLocation;
        emit messageStatus(2,"Could not open file" + picLocation);
        return;
    }

    QString bound="---------------------------723690991551375881941828858";
    QByteArray data(QString("--"+bound+"\r\n").toAscii());
    data += "Content-Disposition: form-data; name=\"action\"\r\n\r\n";
    data += "\r\n";
    data += QString("--" + bound + "\r\n").toAscii();
    data += "Content-Disposition: form-data; name=\"source\"; filename=\""
             +file.fileName()+"\"\r\n";
    data += "Content-Type: image/"+fileInfo.suffix().toLower()+"\r\n\r\n";
    data += file.readAll();
    data += "\r\n";
    data += QString("--" + bound + "\r\n").toAscii();
    data += QString("--" + bound + "\r\n").toAscii();
    data += "Content-Disposition: form-data; name=\"message\"\r\n\r\n";
    data += comment.toAscii();
    data += "\r\n";
    data += "\r\n";

    QNetworkRequest request(uploadUrl);
    request.setRawHeader(QByteArray("Content-Type"),
           QString("multipart/form-data; boundary=" + bound).toAscii());
    request.setRawHeader(QByteArray("Content-Length"),
          QString::number(data.length()).toAscii());
    mCurrentRequest = mNetManager.post(request,data);
    connect(mCurrentRequest,SIGNAL(finished()),this,SLOT(messageResponse()));
}

Saturday, February 11, 2012

Qml FileDialog for symbian anna and belle

I recently ported my Audiobook Reader app for symbian using symbian components. As there is no common QML based file dialog, I need to create my own.

I uploaded my implementation to Gitorious repository here. Currently this code works for only symbian as its used symbian components, but it can be easily ported to work on meego as well.

In this post I will try to explain how this file dialog can be used. Repository also include full working sample.

Lets start with main.cpp file. We need to create instance of FileModel and share it with QML and rest of code is to launch our mainl Qml file.

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

    QDeclarativeView view;

    FileModel fileModel;
    QDeclarativeContext *ctxt = view.rootContext();
    ctxt->setContextProperty("fileModel", &fileModel);

    view.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    view.setResizeMode( QDeclarativeView::SizeRootObjectToView );
    view.setSource(QUrl("qrc:/main.qml"));
    view.show();

    return app.exec();
}
Now QML file which needs to use FileDialog, following code can be used. Here in openFile function, if you want to select Folder/Directory then dirMode should be set to true, if you want to select File than set it to false.
    Page{
        id:page

        function openFile( dirMode ) {
            var component = Qt.createComponent("FileDialog.qml");
            var dialog = component.createObject(page);
            if( dialog !== null ) {
                if( dirMode) {
                    dialog.dirMode = true;
                }
                dialog.fileSelected.connect(fileSelected);
                dialog.directorySelected.connect(directorySelected);
                dialog.open();
            }
        }

        function fileSelected( filePath ) {
            console.debug("File selected:" + filePath);
        }

        function directorySelected( dirPath ) {
            console.debug("Folder selected:" + dirPath);
        }

        tools: ToolBarLayout {
            ToolButton {
                iconSource: "toolbar-back";
                onClicked: {
                    Qt.quit();
                }
            }
            ToolButton {
                text: "File Selection"
                onClicked: {
                    page.openFile(false);
                }
            }
            ToolButton {
                text: "Folder Selection"
                onClicked: {
                    page.openFile(true);
                }
            }
        }
    }
Following are few snaps of FileDialog component running from my Audiobook reader application.

Here is demo of file dialog.

Audiobook Reader for symbian Belle and Anna



I recently ported my Audiobook Reader application to Symbian (supports Anna and Belle).

I struggled a lot while porting this to symbian. For example phonon has some problem with Qt 4.7 on symbian and I wested almost one day to find out solution. If you are also facing similar problem. Then visit this link and this.

Capturing volume key was another problem. I required to use native symbian remote control api to resolve this issue. Visit this link for more info.

And as I use ubuntu machine as development machine, debugging and compilation was another problem.

But finally I was able to port it successfully and now its available on Nokia Store.
Please download it from below.
- Fixed web browser: http://store.ovi.com/content/120217
- Nokia mobile browser: http://store.ovi.mobi/content/120217
Following is demo. Hope you will like it.


Sunday, January 22, 2012

Animating element on curve in QML

I got comment on my post "Animating object along with curve in Qt using QPainterPath" that how similar thing can be achieved in QML. 

I tried to answer that comment in this post.

Originally I intend to achieve it using only QML but did not find any easy way. So I created a custom QDeclarativeItem that uses QPainterPath and implement required functionality.

Well code it quite simple, but it required little hack so that I can use some QML element like PathQuad or PathLine into my c++ code. 

So let's now move to code, I will try to explain as much as I can.

So let's begin with QML, what I want my QML code to look like. My QML has one rect item which act as circle and my custom QML element which act as curve.

I want my curve element to be drawn on screen and I also want circle to follow the curve. In code path is list which contain different kind of path element.

I was not able to intrepreat QML Path element into C++ class , so I end up creating my own path property. My curve also has pointAtPercentage function which provide point at certain progress on curve, which I use with timer to make dot follow that curve.
import QtQuick 1.0
import MyCurve 1.0

Rectangle {
    width: 500; height: 500

    Rectangle {
        id:dot
        width:10;height:10; radius: 5
        color:"steelblue"
    }

    MyCurve {
        id:curve
        path:[
                PathQuad { x: 400; y: 400; controlX: 100; controlY: 600 },
                PathLine{x: 120; y: 120},
                PathQuad { x: 120; y: 25; controlX: 260; controlY: 75 },
                PathQuad { x: 120; y: 100; controlX: -20; controlY: 75 }
            ]
    }

    Timer{
        property variant progress:0;
        interval: 100; running: true; repeat: true
        onTriggered: {
            progress += 0.005;
            if( progress > 1 ) {
                progress  = 0;
            }
            var point = curve.pointAtPercent(progress);
            dot.x = point.x
            dot.y = point.y
        }
    }
}
Now lets look at MyCurve, custom QDeclaraiveItem class, which holds the QPainterPath. MyCurve is quite simple class if we don't include code to interpret PathQuad or PathLine QML element. We could have populated QPainterPath directly in c++ class. But I choose not to do so, to make it more reusable and also that I can try my hands on QDeclarativeListProperty and can show how we can read property of QML element.

#ifndef MYCURVE_H
#define MYCURVE_H

#include <QDeclarativeItem>
#include <QPainterPath>
#include <QGraphicspathItem>
#include <QDeclarativeListProperty>

class MyCurve : public QDeclarativeItem
{
    Q_OBJECT
    Q_PROPERTY(QDeclarativeListProperty<QObject> path READ path)
public:
    explicit MyCurve(QDeclarativeItem *parent = 0);

public slots:
    QPointF pointAtPercent(double Percent);

public:
    QDeclarativeListProperty<QObject> path();

private:
    static void appendItem(QDeclarativeListProperty<QObject> *list,
         QObject *pathItem);

    void appendPathQuad( QObject* pathQual);
    void appendPathLine( QObject* pathLine);

private:    
    QGraphicsPathItem* _path;
    QPainterPath _painterPath;
};
#endif // MYCURVE_H
Only Interesting about header is appendItem static method, which I will explain after showing its implementation. So here is implementation of header.
#include "mycurve.h"
#include <QDebug>
#include <QDeclarativeItem>
#include <QPen>

MyCurve::MyCurve(QDeclarativeItem *parent) :
    QDeclarativeItem(parent),_path(0),_startX(0),_startY(0)
{
    _path = new QGraphicsPathItem(this);
    _path->setPen(QPen(Qt::blue));
}

QPointF MyCurve::pointAtPercent(double Percent) {
    return _painterPath.pointAtPercent(Percent);
}

QDeclarativeListProperty<QObject> MyCurve::path()
{
    return QDeclarativeListProperty<QObject>(this,0,&MyCurve::appendItem);
}

void MyCurve::appendItem(QDeclarativeListProperty<QObject> *list, 
    QObject *pathItem)
{
    MyCurve *myCurve = qobject_cast<MyCurve *>(list->object);
    if (myCurve) {
         if( QString(pathItem->metaObject()->className())
                == QString("QDeclarativePathQuad") ) {
             myCurve->appendPathQuad(pathItem);
         } else if (QString(pathItem->metaObject()->className()) 
               == QString("QDeclarativePathLine")){
             myCurve->appendPathLine(pathItem);
         }
       }
}

void MyCurve::appendPathQuad( QObject* pathQuad) {
    double x = pathQuad->property("x").toDouble();
    double y = pathQuad->property("y").toDouble();
    double controlX = pathQuad->property("controlX").toDouble();
    double controlY = pathQuad->property("controlY").toDouble();

    _painterPath.quadTo(controlX,controlY,x,y);
    _path->setPath(_painterPath);
}

void MyCurve::appendPathLine( QObject* pathLine) {
    double x = pathLine->property("x").toDouble();
    double y = pathLine->property("y").toDouble();
    _painterPath.lineTo(x,y);
    _path->setPath(_painterPath);
}
There are quite a few interesting things here.

Usage of QDeclarativeListProperty(I am using it for first time), QDeclarativeListProperty is used to create list of property in QML. To operate on QDeclarativeListProperty, we need to provide static method which take pointer of list object and list item. appendItem is similar static method which add path element to our QPainterPath. To know more how other operation can be implemented on QDeclarativeListProperty, please visit this or this link.

In above code I am using metaObject to identify which QML Path element is being added by appendItem ( which is kind of dirty hack ) and after identifying element I am using property method to get its value and finally using those value to call appropriate QPainterPath method.

And finally here is how it looks,

Friday, December 9, 2011

Using QDeclarativeImageProvider to load QPixmap to QML Image element

Recently for my mobile application, I required cache image from network and use that in QML application. Prior to caching, I was using WebView element to show image from network, but I needed to show that image multiple places, to avoid multiple network request I decided to prefetch network image and show that using Image element.

To make it work, I downloaded network image to QPixmap using QNetworkAccessManager and then used QDeclarativeImageProvider to provide cached QPixmap to Image element.

As per documentation "The QDeclarativeImageProvider class provides an interface for supporting pixmaps and threaded image requests in QML."  I also used it as proxy image provider. When actual Image data is not available my image provider class will provide some dummy image and when actual data is available it will provide actual image data.

Following is my code for my custom image provider derived from QDeclarativeImageProvider.

In following code, by providing QDeclarativeImageProvider::Pixmap as ImageType, I am saying I will povide QPixmap as Image type and in this case requestPixmap API will be called by declarative engine to fetch image. You can also use QDeclarativeImageProvider::Image, to provide QImage to Image and in that case requestImage API will be called.

#include <QDeclarativeImageProvider>

class ImageProvider: public QDeclarativeImageProvider
{
public:
    ImageProvider(ImageManager* manager)
        : QDeclarativeImageProvider(QDeclarativeImageProvider::Pixmap),
          mManager(manager)
    {}

    QPixmap requestPixmap(const QString &id, QSize *size, 
        const QSize &requestedSize)
    {
        int width = 320;
        int height = 53;

        QPixmap result;

        if( mManager->imageData() == 0 ) {
     QPixmap pixmap(requestedSize.width() > 0?requestedSize.width():width,
             requestedSize.height() > 0 ?requestedSize.height():height);

            pixmap.fill(QColor(id).rgba());

            if ( size ) *size = QSize(width, height);
            result = pixmap;
        } else {

            result = *mManager->imageData();
            if ( size ) *size =result.size();

            if (requestedSize.isValid()) {              
                result = result.scaled(requestedSize,Qt::IgnoreAspectRatio);
            } 
        }
        return result;
    }

private:
    ImageManager* mManager;
};
Now custom image provider is ready, but we need to register our image provide to declarative engine, so that it will now forward image loading request to our image provider. To do that, we need to use QDeclarativeEngine::addImageProvider API, as described in following code. Here in addImageProvider API, "MyImage" is provider name, that will be used in QML to indicate that our custom image provider should be used.
QScopedPointer view(new QDeclarativeView());
view->engine()->addImageProvider(QLatin1String("MyImage"), 
    new ImageProvider(ImageManager::instance()));
Now we are ready to use our custom image provider with Image element, like shown below. Here in Image.source we providing path as image://MyImage, which will tell system to use MyImage image provider and remaining part of url will be used as id in requestPixmap or requestImage parameter. Which can be used to decide what kind of image data to provide.
import QtQuick 1.0

Rectangle {
    id:container
    width: 320;height: 53
    anchors.horizontalCenter: parent.horizontalCenter    

    Connections{
        target: ImageManager
        onImageAvailable:{
            myImage.source = "image://MyImage/test"
        }
    }

    Image {
        id: myImage
        anchors.centerIn: parent
        source: "image://MyImage/"+container.color
    }
}
This is all that is needs to be done to implement custom image provide. Hope it will be usefull.

Saturday, November 26, 2011

Using custom Font with Qt

Recently in one of my application I wanted to use custom font and in little time I figured out that Qt has vary nice support to use custom font with both Qt C++ and QML.

I used following code in my application. Here is output of below code.


Following is code to use custom font with Qt C++.
#include <QPainter>
#include <QFontDatabase>

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent)
{
    QFontDatabase::addApplicationFont("sandsped.ttf");
}

void MyWidget::paintEvent(QPaintEvent */*event*/) {
    QPainter painter(this);
    painter.drawText(10,20,"Default Font");
    painter.setFont(QFont("Sandoval Speed"));
    painter.drawText(10,50,"Custom Font");
}


Following is code to use custom font with QML.
    FontLoader { id: myFont; source: "sandsped.ttf" }

    Column {
        spacing: 30
        anchors.horizontalCenter: parent.horizontalCenter
        Text {
            text: "Default Font"
        }

        Text {
            font.family: myFont.name
            text: "Custom Font";
        }
    }

Thursday, November 17, 2011

Virtual Joystick with QML

Recently out of curiosity I tried to created virtual joystick, which nowadayx s used quite frequently touch based games.

Well my implementation still required some improvement to provide real feel of joystick but its still quite useful. Here is output.

To test my joystick, I also created a sprite which moves in almost all direction.

Here is my QML code for joystick. I basically used two circle and checking inner circle position with outer circle and deciding direction. I am not describing code, but tried to put necessary comment in code.
import QtQuick 1.0

Item {
    id:joyStick;
    property int offset:30;

    signal dirChanged(string direction);
    signal pressed();
    signal released();

    Rectangle {
        id:totalArea
        color:"gray"
        radius: parent.width/2
        opacity: 0.5
        width:parent.width;height:parent.height
    }

    Rectangle{
        id:stick
        width:totalArea.width/2; height: width
        radius: width/2
        x: totalArea.width/2 - radius;
        y: totalArea.height/2 - radius;        
        color:"black"
    }

    MouseArea{
        id:mouseArea
        anchors.fill: parent

        onPressed: {
            joyStick.pressed();
        }

        onMousePositionChanged: {            
         //(x-center_x)^2 + (y - center_y)^2 < radius^2
         //if stick need to remain inside larger circle
         //var rad = (totalArea.radius - stick.radius);
         //if stick can go outside larger circle
         var rad = totalArea.radius;
         rad =  rad * rad;

         // calculate distance in x direction
         var xDist = mouseX - (totalArea.x + totalArea.radius);
         xDist = xDist * xDist;

         // calculate distance in y direction
         var yDist = mouseY - (totalArea.y + totalArea.radius);
         yDist = yDist * yDist;

         //total distance for inner circle
         var dist = xDist + yDist;            

         //if distance if less then radius then inner circle is inside larger circle
         if( rad < dist) {
             return;
         }

         //center of larger circle
         var oldX = stick.x; var oldY = stick.y;
         stick.x = mouseX - stick.radius;
         stick.y = mouseY - stick.radius;

         //using L R U D LU RU LD RD for describe direction
         var dir="";

         //check if Right or left direction, 
         //by checking if inner circle's y is near center of larger circle
         if( stick.y >= totalArea.radius - stick.radius - joyStick.offset 
 && stick.y+stick.height <= totalArea.radius + stick.radius + joyStick.offset) {
             if( stick.x + stick.radius > totalArea.x + totalArea.radius) {
                 dir = "R";
             } else if( stick.x < totalArea.x + totalArea.radius) {
                 dir = "L";
             }
         }
         //check if Up or Down direction, 
         //by checking if inner circle's x is near center of larger circle
         else if( stick.x >= totalArea.radius - stick.radius - joyStick.offset 
 && stick.x + stick.width <= totalArea.radius + stick.radius + joyStick.offset) {
            if( stick.y + stick.radius > totalArea.y + totalArea.radius) {
                 dir = "D";
            } else if( stick.y < totalArea.y + totalArea.radius) {
                 dir = "U";
            }
         }
         //check if Up Left or Up Right direction,
         //by checking if inner circle is near one of top corner of larger circle
         else if( stick.y < totalArea.radius - stick.radius ) {
            if( stick.x + stick.radius > totalArea.x + totalArea.radius) {
                dir = "R";
            } else if( stick.x < totalArea.x + totalArea.radius) {
                dir = "L";
            }
            dir = dir +"U";
         }
         //check if Down Left or Down Right direction,
         //by checking if inner circle is near one of bottom corner of larger circle
         else if ( stick.y + stick.radius >= totalArea.radius + stick.radius ) {
            if( stick.x + stick.radius > totalArea.x + totalArea.radius) {
               dir = "R";
            } else if( stick.x < totalArea.x + totalArea.radius) {
               dir = "L";
            }
            dir = dir +"D";
         }

         joyStick.dirChanged(dir);
        }

        onReleased: {
            //snap to center
            stick.x = totalArea.width /2 - stick.radius;
            stick.y = totalArea.height/2 - stick.radius;

            joyStick.released();
        }
    }
}

Follwing my code for sprite used in above video.
import QtQuick 1.0

Item {
    id:sprite
    width: 50; height: 50
    clip:true
    property alias running: timer.running;
    property int frameCount: 5
    property int frame:0
    property int row:0

    property int xDir:0;
    property int yDir:0;

    Image{
        id:image
        source:"man.png"
        x:-sprite.width * sprite.frame;
        y:-sprite.height * sprite.row;
    }

    function changeDirection(direction) {
        if( direction === "L") {
            sprite.row=6;
            sprite.xDir = -1;
            sprite.yDir = 0;
        } else if( direction === "R") {
            sprite.row=2;
            sprite.xDir = 1;
            sprite.yDir = 0;
        } else if( direction === "U") {
            sprite.row=4;
            sprite.xDir = 0;
            sprite.yDir = -1;
        } else if( direction === "D") {
            sprite.row=0;
            sprite.xDir = 0;
            sprite.yDir = 1;
        } else if( direction === "RU") {
            sprite.row = 3;
            sprite.xDir = 1;
            sprite.yDir = -1;
        } else if( direction === "LU") {
            sprite.row = 5;
            sprite.xDir = -1;
            sprite.yDir = -1;
        } else if( direction === "RD") {
            sprite.row = 1;
            sprite.xDir = 1;
            sprite.yDir = 1;
        } else if( direction === "LD") {
            sprite.row = 7;
            sprite.xDir = -1;
            sprite.yDir = 1;
        }
    }

    function nextFrame() {
        sprite.frame = ++sprite.frame  % sprite.frameCount
        sprite.x = sprite.x + 5* sprite.xDir;
        sprite.y = sprite.y + 5* sprite.yDir;
    }

    Timer {
       id:timer
       interval: 150; running: false; repeat: true
       onTriggered: {
           nextFrame();
       }
    }
}
Finally, main qml file which include both joystick and sprite.
import QtQuick 1.0

Image {
    width: 854 ;  height:480    
    source:"grass.jpg"
    fillMode: Image.Tile

    Sprite{
        id:man
        x:parent.width/2 ; y: parent.height/2;
    }

    Connections {
        target: joyStick
        onDirChanged:{
            man.changeDirection(direction)
        }

        onPressed:{
            man.running=true;
        }

        onReleased:{
            man.running=false;
        }
    }

    Joystick{
        id:joyStick
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.bottomMargin: 10
        anchors.leftMargin: 10
        width:150;height:150
    }
}


Saturday, October 15, 2011

Audiobook Reader now available for N9 / N950 ( Harmattan ) on Nokia Store

I recently updated my Audiobook reader application for N9 Harmattan platform. It is also supported on N950. You can download it from Nokia Store from here.





For those who dont know about this application, Audiobook reader is simple Audiobook player which lets you add audiobook with single large audio file or folder with audio files for each chapter. It automatically bookmark the last position of audiobook and resume playback from that position. It also allow to add custom bookmark and playback from certain chapter from Audiobook.

For N9, I completely reimplemented UI layer to give native look and feel. For this version I am also showing book cover image, downloaded from AWS to give more feel of book.




Same as N900 version, this version also support custom bookmark support and chapter selection support. Volume can be changed by using Hardware key.


Saturday, September 24, 2011

Crazy Chickens game available on N9/N950 Harmattan

Recently I ported my Crazy Chickens game for Harmattan / Maemo6. Its now available on Ovi Store.

Find out more information about this game here. Following are few snaps of game from Harmattan version.






Sunday, September 4, 2011

Porting Qt app to Harmattan

As I received Nokia N9 Dev kit from Qt Ambassador program, I started working on porting my existing Maemo 5 application to Maemo 6 (Harmattan/Meego) platform.

It seems from documentation that preferred way to create Meego application is by using QML and com.meego components. In order to make my Qt and QML application to work correctly on meego I needed to make quite a few changes.

First thing I noticed is that, Qt Widget are available on harmattan but that just for backword compatiblity and dose not provide native look and feel for Harmattan platform. That mean Qt Widget library are kind of useless on harmattan. We need to use meego touch library or meego QML component.

Some of my application were QWidget based or some were Graphics View based. I ported most of application to use QML and If i can not port to use QML then I  used QDeclarativeItem to load that component to QML.

For some of my application I was locking orientation, using "WA_Maemo5PortraitOrientation" flag in view.setAttribute(Qt::WA_Maemo5PortraitOrientation, true); API call, But on Harmattan I need to use following code in QML page.
 Page{
        orientationLock: PageOrientation.LockPortrait
    }
To make application full screen, I need to disable statusbar and toolbar from PageStackWindow. I used following code

PageStackWindow {
    showStatusBar: false
    showToolBar: false
}
In one of my application I was using GraphicsView framework, I loaded graphics view to QML using QDeclarativeItem and QGraphicsProxyWidget. Visit following link for more info. 

But after GraphicsView loaded to QML, view was displaying some white area that initially I was not able to remove. After a white I realized it was frame for graphics view. I removed it by using setFrameStyle API.
setFrameStyle(QFrame::NoFrame);
Desktop file also needs to be changed to locate icon correctly and to launch only single instance of application.
[Desktop Entry]
Encoding=UTF-8
Version=0.1
Name=appname
GenericName=app name
Comment=some comment
Exec=/usr/bin/single-instance /usr/bin/appname
Terminal=false
Type=Application
Icon=/usr/share/icons/hicolor/64x64/apps/icon.png
Also in control file, to make your application user application and not system component, we need to add following flag.
Maemo-Flags: visible
I used following in my project file to transfer icon file to proper location.
unix  {
    #VARIABLES
    isEmpty(PREFIX) {
        PREFIX = /usr
    }
    BINDIR = $$PREFIX/bin
    DATADIR =$$PREFIX/share

    DEFINES += DATADIR=\\\"$$DATADIR\\\" PKGDATADIR=\\\"$$PKGDATADIR\\\"

    INSTALLS += target desktop icon64

    target.path =$$BINDIR

    desktop.path = $$DATADIR/applications
    desktop.files += ./image/$${TARGET}.desktop

    icon64.path = /usr/share/icons/hicolor/64x64/apps/
    icon64.files += ./image/$${TARGET}.png
}
I also faced segmentation fault while testing Webview with emulator, but on device it works fine.

That's all, most of my experience was smooth while porting and did not struggled much.