V-Play for Android Developers

This document contains code samples, design patterns and useful information when looking at V-Play from an Android developer perspective. Use this guide to build upon your Android coding knowledge and quickly learn the similarities and differences compared to cross-platform development with V-Play.

Compiling your V-Play app for Android will present you with a native application package (.apk), which you can run on any Android device or publish in the Google Play Store. Similar to native Android development, the build process relies on the JDK as well as Android SDK and NDK.

If you do not yet have V-Play or the required Android build tools installed, you can have a look at these guides:

Why to use V-Play?

V-Play utilizes QML + Javascript as the main coding language and is based on Qt, a well-known and feature-rich C++ framework. This allows to save up to 90% of code compared to other languages and frameworks. It is also a cross-platform tool. This means you can compile your application for different platforms using the same code base. In this area, V-Play supports Android, iOS or even Desktop platforms and embedded systems.

One of the biggest advantages of V-Play lies in the way you can compose your UI views, create layouts and add animations. This is where the power of QML comes into action. V-Play moves the view composition and widget rendering away from the platform directly into your app. Instead of heavy-weight and hard to animate widgets that are rendered by the platform, you can create your UI with easily extensible and customizable items.

Building your UI this way saves code, makes it easier to maintain and feels natural. It also follows the trend to move away from 'cookie cutter' apps that were common a few years ago. Modern apps focus more on custom designs that follow your brand and provide a rich user experience.

The simplicity of QML speeds up development, but the customizability and extensibility make it so powerful. You have full control over your UI items and layout while taking advantage of theme-able UI components that match the native user experience of Android or iOS widgets. Combined with ready-to-use native features, backend services and the power of C++ Qt, V-Play is the perfect choice for any app use-case.

It is also possible to put your existing Android knowledge to use and extend V-Play with custom native integrations if needed. V-Play already offers many cross-platform plugins that integrate native frameworks and communicate with Android (or iOS). For an overview of how to tackle different tasks in V-Play, we've summed up the most important topics and questions for you:

Views

What is the equivalent of a View in V-Play?

In Android, everything that you see on the screen is a View. For V-Play, the same can be said for the basic QML Item type. It comes with everything you need to show, layout and compose UI elements of your app.

But there are a few differences when it comes to rendering. Based on your UI code that consists of QML Items, the V-Play application builds a tree of Item instances. You do not require to call invalidate to redraw those Items, as it is for Views on Android. Whenever Items change, the QML engine updates the UI automatically.

The QML rendering engine is a highly-optimized piece of C++ code, which renders your QML UI within a native view in your Android app. Lightweight, fast and easy to work with. The V-Play App Components offer many different items that incorporate the Android Material Design guidelines. With these types, you can use the power of QML to create your Android app. If you run the app on iOS, the components will change their look to use native iOS styles and gestures instead - without touching the code.

Android iOS

How do I update Items?

This is a question that you no longer need to worry about. The QML Items update automatically if required. Furthermore, whenever properties of an Item change, other elements get notified automatically. This is possible with the power of property bindings:

 import VPlayApps 1.0
 import QtQuick 2.0

  App {
    // property for counting # of clicks
    property int clickCount: 0

    // main content page with a text
    Page {

      // text, anchored to the page center
      AppText {
        text: "You clicked " + clickCount + " times!" // property binding!
        anchors.centerIn: parent
      }

      // handle touch/click on full page
      MouseArea {
        anchors.fill: parent
        onClicked: clickCount = clickCount + 1 // AppText updates automatically
      }
    }
  }

These few lines of QML code present us with a full-screen Page that comes with a white background. It contains a text, which is centered and prints the value of the App's clickCount property. A touch anywhere on the Page is handled by the MouseArea, which increases the counter.

Due to the property binding feature, each change of the clickCount property triggers a new evaluation of the AppText's text property. This is because the bound expression relies on the clickCount property. The AppText then updates accordingly and shows the new text value.

How do I lay out my Items? Where is my XML layout file?

In V-Play, you use QML to layout your app. By nesting QML items you can compose UI elements on the fly. For example, to show a text and a button on a page:

Android iOS

 import VPlayApps 1.0
 import QtQuick 2.0

 // App is the root item and represents the app window
 App {

   // NavigationStack can hold pages includes a navigation bar
   NavigationStack {

     // the main page with a title and content items
     Page {
       title: "Sample App"

       // centered text item
       AppText {
         text: "I am centered."
         anchors.centerIn: parent
       }

       // button at the bottom
       AppButton {
         text: "I am centered at the bottom."
         onClicked: console.log("Button clicked!")
         anchors.horizontalCenter: parent.horizontalCenter
         anchors.bottom: parent.bottom
       }
     }
   }
 }

Every V-Play app begins with a single App component defined as the root of the QML tree. Every app then usually includes a navigation item and some Page items for your content views.

How do I add or remove a component from my layout?

Android requires you to use addChild() or removeChild() on a parent to add or remove child views. While QML also has these possibilities, there are easier ways to dynamically show or hide items. If you don't mind keeping the item instance in the QML tree alive, you can also control the visibility of each item as you like. Items thus do not require to be re-created and can keep their state while hidden.

This example toggles between two items with a FloatingActionButton:

 import VPlayApps 1.0

 App {
   Page {
     AppText {
       id: appTextItem
       text: "Some Text"
       anchors.centerIn: parent
     }
     AppButton {
        text: "A Button"
        visible: !appTextItem.visible // hide button if text is visible
        onClicked: console.log("Button clicked!")
        anchors.centerIn: parent
     }
     FloatingActionButton {
       icon: IconType.refresh
       visible: true // otherwise FloatingActionButton only shows when run on Android
       onClicked: appTextItem.visible = !appTextItem.visible // show/hide text
     }
   }
 }

How do I animate an Item?

In Android, views offer the animate() method or you can add animations with XML. V-Play offers an extensive animation framework with the Animation QML components. It is possible to animate every basic property of your UI elements. You can even define behaviors to automatically animate properties whenever they change.

The following example allows to fade a text by animating its opacity:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Page {

     // button at the bottom allows to toggle the text
     AppButton {
      anchors.horizontalCenter: parent.horizontalCenter
      anchors.bottom: parent.bottom
      text: "Toggle Text Item"
      onClicked: textItem.opacity = textItem.visible ? 0 : 1 // toggle textItem visibility
     }

     // centered text which fades when opacity changes
     AppText {
       id: textItem
       anchors.centerIn: parent
       text: "Hello World!"
       visible: opacity != 0 // also set invisible when fully transparent

       // when opacity changes ...
       Behavior on opacity {
         NumberAnimation { duration: 500 } // ... animate to reach new value within 500ms
       }
     }

   }
 }

Here is another example how you can create complex animations. For this, you can use the SequentialAnimation and ParallelAnimation types to nest your animations. You can combine those types in any order.

 import VPlayApps 1.0
 import QtQuick 2.8

 App {
   NavigationStack {
     Page {
       title: "Complex Animation"

       AppButton {
         anchors.centerIn: parent
         text: "Move!"
         flat: false
         onClicked: {
           // Start the animation by calling start() of the top-most item
           complexAnimation.start()
         }
       }

       Rectangle {
         id: rectangle
         width: dp(100)
         height: dp(100)
         color: "black"
       }

       // All child animations will be executed one after the other
       SequentialAnimation {
         // You can start the whole animation by calling start() of the top-most item
         id: complexAnimation

         // 1. Move to right
         NumberAnimation {
           target: rectangle
           property: "x"
           to: dp(200)
           duration: 1000
         }

         // 2. Move down and change color
         // All child animations will be executed in parallel
         ParallelAnimation {
           NumberAnimation {
             target: rectangle
             property: "y"
             to: dp(400)
             duration: 1000
             easing.type: Easing.InOutQuad
           }
           ColorAnimation {
             target: rectangle
             property: "color"
             to: "blue"
             duration: 1000
           }
         }

         // 3. Move left, change color and rotate
         // All child animations will be executed in parallel
         ParallelAnimation {
           NumberAnimation {
             target: rectangle
             property: "x"
             to: 0
             duration: 1000
           }
           ColorAnimation {
             target: rectangle
             property: "color"
             to: "black"
             duration: 1000
           }
           NumberAnimation {
             target: rectangle
             property: "rotation"
             from: 0
             to: 360
             duration: 1000
           }
         }

         // 4. Move up
         NumberAnimation {
           target: rectangle
           property: "y"
           to: 0
           duration: 1000
           easing.type: Easing.InBack
         }
       }
     }
   }
 }

You can find even more animation examples on this page: Add Animations to your App

How do I use a Canvas to draw/paint?

The Canvas item allows to draw straight and curved lines, simple and complex shapes, graphs, and referenced graphic images. It can also add text, colors, shadows, gradients, and patterns, and do low-level pixel operations.

The width and height properties of the Canvas item define the drawing area. If it requires rendering, the paint signal fires. When handling the signal, you can draw to the Canvas using a Context2D object:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Page {
     Canvas {
       id: mycanvas
       width: 100
       height: 200
       onPaint: {
         var ctx = getContext("2d");
         ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
         ctx.fillRect(0, 0, width, height);
       }
     }
   }
 }

How do I build custom QML Items?

Each .qml file of your project is an own reusable QML Component. The specified root QML Item determines the base component, which your new item extends. The new QML type can then add properties, signals and functions, which form the public interface of the component.

To define the layout for the item, add some child elements and position them in the view. Each child element may also be extended with new features and properties directly where it is used. You do not require to create an own QML Item to make small additions to a single item instance in your UI.

The following example shows a clickable CustomButton.qml component with a background and text. Once imported, you can use the new type in your app:

 import VPlayApps 1.0
 import "relative-path-to-directory-of-custom-button"

 App {
   CustomButton {
     anchors.centerIn: parent

     // new count property only for this button instance
     property int count: 0

     text: "You clicked "+count+" times."
     backgroundColor: "yellow"
     onClicked: count++
   }
 }
 import QtQuick 2.0

 // CustomButton extends Item, which is the base type for all UI elements
 Item {
   // the default (implicit) size is based on the size of the child text element
   // the width and height thus depend on the actual text value
   implicitWidth: textItem.implicitWidth
   implicitHeight: textItem.implicitHeight

   // public properties and signals
   property color backgroundColor: "green"
   property string text: "Click Me!"
   signal clicked()

   // child elements
   Rectangle {
     anchors.fill: parent
     color: parent.backgroundColor
   }

   Text {
     id: textItem // id for referencing this text item within the component
     text: parent.text
     anchors.centerIn: parent
   }

   // handle touch/click and fire signal when a click happens
   MouseArea {
     anchors.fill: parent
     onClicked: parent.clicked() // emits clicked signal of CustomButton
   }
 }

Activities and Intents

What is the equivalent of an Intent in V-Play?

Intents in Android are mainly used for navigating between Activities and communicating with components. V-Play does not require Intents to navigate between app pages and handles everything directly in QML.

You can rely on the Navigation Components to switch between different Pages in your app, all within the same Activity:

 import VPlayApps 1.0

 App {
   Navigation {

     NavigationItem {
       title: "Home"
       icon: IconType.home

       NavigationStack {
         Page {
          title: "Main Page"
         }
       }
     }

     NavigationItem {
       title: "Lists"
       icon: IconType.list

       NavigationStack {
         Page {
          title: "Lists"
         }
       }
     }

   }
 }

If required, you can still work with and handle Intents through native integrations to your V-Play app.

What is the equivalent of startActivityForResult()?

Apart from the app Navigation, which provides the main menu for your app, the NavigationStack is the main component for navigating back and forth between different pages.

For passing data between pages, the easiest solution is to make relevant settings or properties available in a common parent scope. Public properties, functions and signals of an ancestor in the QML tree are available for direct access:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   id: app

   property int count: 0

   // main page
   NavigationStack {
     Page {
       id: mainPage
       title: "Main"

       Column {
         anchors.centerIn: parent

         // text to show the current count and button to push the second page
         AppText {
           anchors.horizontalCenter: parent.horizontalCenter
           text: "Count " + app.count
         }
         AppButton {
           text: "Push Counter Page"
           onClicked: mainPage.navigationStack.push(counterPageComponent)
         }
       }
     }
   }

   // inline-definition of a component, which is later pushed on the stack
   Component {
     id: counterPageComponent
     Page {
       title: "Change Count"
       property Page target: null

       Column {
         anchors.centerIn: parent

         // buttons to increase or decrease the count, which is displayed on the main page
         AppButton {
           text: "Count ++"
           onClicked: {
             app.count++
           }
         }
         AppButton {
           text: "Count --"
           onClicked: {
             app.count--
           }
         }
       }
     }
   }
 }

How do I listen to Android activity lifecycle events?

Your V-Play app window runs within a single activity on Android. For listening to lifecycle events, you can add handlers for the App::applicationPaused or App::applicationResumed signals:

 import VPlayApps 1.0

 App {

   onApplicationPaused: console.log("Application paused.")
   onApplicationResumed: console.log("Application resumed.")

   // ...
 }

Async UI and Networking

What is the equivalent of runOnUiThread() in V-Play?

To avoid operations blocking your UI, Android requires to keep the main thread free at all times. As V-Play relies on QML and Javascript, updates to the UI are already handled in a highly asynchronous and event-driven way. You weave-in your Javascript code as part of signal handlers that execute when certain events or user interactions happen. The QML rendering engine is highly optimized, so you do not need to worry about blocking the UI when adding your view logic.

Communication with your application backend is also easy, as you can use the XmlHttpRequest Element asynchronously. This example fetches JSON response containing the URL to an image. The request happens asynchronously. The returned URL is then set as the AppImage source, which is able to asynchronously load an image from an URL:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {

   property string serverUrl: "https://jsonplaceholder.typicode.com/photos/1"
   property var jsonData: undefined

   // handler function to be executed when the App Item is fully created, starts web requests
   Component.onCompleted: {
     // the 3rd parameter of open(...) is the asynchronous flag
     var httpRequest = new XMLHttpRequest();
     httpRequest.open("GET", serverUrl, true);

     // define function to handle result of request
     httpRequest.onreadystatechange = function() {
       if (httpRequest.readyState == httpRequest.DONE) {
         var serverResponse = httpRequest.responseText;
         jsonData = JSON.parse(serverResponse); // parse result and set jsonData property
       }
     }

     // start request
     httpRequest.send();
   }

   Page {

     // just some spinning icon to show asynchronous loading of image
     Icon {
       anchors.centerIn: parent
       icon: IconType.refresh
       NumberAnimation on rotation {
         loops: Animation.Infinite
         from: 0
         to: 360
         duration: 1000
       }
     }

     AppImage {
       // expression for source relies on the jsonData property (property binding!)
       // the REST api returns the web url to an image, which we can set directly to load the image
       source: jsonData !== undefined ? jsonData.url : ""
       anchors.fill: parent
       fillMode: AppImage.PreserveAspectFit
       // additionally you can make the image loading itself asynchronous
       // this is recommended for images loaded from web source
       asynchronous: true
     }
   }
 }

After request completion, the result is stored to the jsonData property. The expression for the image source relies on the property, so the AppImage will automatically update and show the image as soon as the data arrives - nothing more to do.

How to Access REST Services with Qt and V-Play?

REST and RESTful web services are the most common way to access data through the Internet. This article gives detailed insights on how to create an App and connect to a REST service with V-Play: How to Access REST Services: Weather Service Example App

How do you move work to a background thread?

For long-running and data-intense operations, it still makes sense to actively use a separate thread and notify your UI once the work is done. To quickly spawn a new thread in QML, you can add a WorkerScript item:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   AppText {
     id: myText
     text: 'Click anywhere'
   }

   WorkerScript {
     id: myWorker
     source: "script.js" // script to run on new thread

     onMessage: myText.text = messageObject.reply
   }

   MouseArea {
     anchors.fill: parent
     onClicked: myWorker.sendMessage({ 'x': mouse.x, 'y': mouse.y })
   }
 }

The above worker script specifies a JavaScript file, script.js, which is handled in a new thread. Here is an example script.js, which simply returns the passed mouse position:

 WorkerScript.onMessage = function(message) {
     // ... long-running operations and calculations are done here
     WorkerScript.sendMessage({ 'reply': 'Mouse is at ' + message.x + ',' + message.y })
 }

For more control over your threads and the best possible performance, you also have the full power of Qt C++ at your hands. You can find a guide how to mix V-Play QML code with Qt C++ components here: How to Expose a Qt C++ Class with Signals and Slots to QML.

Stepping into the C++ world also gives access to e.g. advanced networking features like a socket or Bluetooth connection.

The demo is also available with the V-Play SDK here: <Path to V-Play>/Examples/V-Play/appdemos/cpp-qml-integration

Project structure & resources

Where do I store my resolution-dependent image files?

V-Play projects come with an assets folder where you can place all your images. To bundle the folder content along with your application, the *.pro project configuration contains the following line:

 DEPLOYMENTFOLDERS += assets

In addition, your project also holds an android folder which handles platform-specific configurations like the AndroidManifest.xml, build.gradle or your app-icons in the res sub-folder. In the same manner, the respective platform configuration for ios is found in the ios folder.

Similar to Android, you can add different images per density bucket ldpi (ld), mdpi (sd), hdpi (hd) and xhdpi (hd2) in separate directories. In V-Play, you can do that with the MultiResolutionImage component. It automatically chooses the best image version for each device's screen. The App component internally uses such a MultiResolutionImage.

By default V-Play allows you to provide three different images, for example:

  • imageSwitching.png (e.g. 50×20 px)
  • +hd/imageSwitching.png (e.g. 100×40 px)
  • +hd2/imageSwitching.png (e.g. 200×800 px)

This code snippet selects the best version of the above image automatically:

 import VPlayApps 1.0

 App {

   AppImage {
     source: "../assets/imageSwitching.png" // relative path from QML file to image

     // for the size, we specify density independent pixels
     width: dp(50)
     height: dp(20)
   }

 }

To specify density-independent sizes for UI elements, you can rely on the App::dp() function. The V-Play Apps Components are already set up to have the same physical size on all screens - regardless of their density.

For more information about density-independence in V-Play, see Supporting Multiple Screen Sizes & Screen Densities with V-Play Apps.

Where do I store strings? How do I handle localization?

V-Play is based on the Qt platform, so you can rely on Qt Linguist tools for your translations. Adding translations to your app then requires these three steps:

  • Use the qsTr() function to mark texts for translation in your QML code.
  • Generate translation files for all strings (in XML format).
  • Translate the texts.
  • Release translation binaries for usage in your app.

See here for a full guide about internationalization and string translation: How to Make a Multi Language App or Game with V-Play

What is the equivalent of a Gradle file? How do I add dependencies?

V-Play creates a native Android APK using the same Android build tools that you already know. To configure the Android app and build, you have access to the AndroidManifest.xml and build.gradle in the android folder of your project.

When working with V-Play Plugins for native features, only a single dependency per plugin includes all required frameworks. See the plugin documentation page for more information about plugin integration.

Layouts

What is the equivalent of a LinearLayout, RelativeLayout or ScrollView?

There are many different layouting mechanisms and components available with V-Play. For a short introduction, please see Create Layouts and Position Components in Your App.

How do I handle landscape transitions in V-Play?

The App::portrait or App::landscape properties allow to optimize your layout for different orientations. Similar other properties in QML, you can add handlers for property changes or use property bindings to adapt the UI automatically.

 import VPlayApps 1.0

 App {
   id: app
   onPortraitChanged: {
     if(portrait)
       console.log("orientation changed to portrait")
     else
       console.log("orientation changed to landscape")
   }

   AppText {
     text: app.landscape ? "Landscape Mode" : "Portrait Mode"
     anchors.centerIn: parent
   }
 }

You can also manually change the orientation settings at runtime, e.g. like this:

 import VPlayApps 1.0
 import QtQuick 2.5

 App {
   NavigationStack {
     Page {
       title: "Orientation Lock"

       Column {
         AppButton {
           text: "Lock to landscape"
           onClicked: nativeUtils.preferredScreenOrientation = NativeUtils.ScreenOrientationLandscape
         }
         AppButton {
           text: "Remove orientation lock"
           // Resets to the orientation defined in AndroidManifest.xml / Project-Info.plist
           onClicked: nativeUtils.preferredScreenOrientation = NativeUtils.ScreenOrientationDefault
         }
       }
     }
   }
 }

Gesture detection and touch event handling

How do I add an onClick listener to an item in V-Play?

If an item already supports user interaction, you can directly handle the events in your code. The following example adds an AppButton and handles the clicked signal:

 import VPlayApps 1.0

 App {

   AppButton {
     text: "Click Me!"
     anchors.centerIn: parent
     onClicked: text = "Thanks!"
   }

 }

To handle clicks for a custom Item, you can add a MouseArea:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {

    Rectangle {
     width: dp(200)
     height: dp(200)
     color: "lightyellow"
     anchors.centerIn: parent

     MouseArea {
       anchors.fill: parent
       onClicked: parent.color = "lightgreen"
     }
   }

 }

How do I handle other gestures on items?

You can work with different MouseArea signals to adapt it for your use-case. However, the MouseArea can only handle a single touch point. For more information on gestures and handling multiple touch points, please see: Handle Touch and Gestures in Your App.

ListViews & Models

What is the alternative to a ListView in V-Play?

The easiest way to create a list is to use the AppListView type together with a SimpleRow delegate for the list cells:

Android iOS

 import VPlayApps 1.0

 App {
   NavigationStack {
     Page {
       title: "Basic List Example"

       AppListView {
         delegate: SimpleRow {}
         model: [
           {
             text: "Apple",
             detailText: "A delicious fruit with round shape",
             icon: IconType.apple
           },

           {
             text: "Beer",
             detailText: "A delicous drink",
             icon: IconType.beer
           }
         ]
       }
     }
   }
 }

The model-delegate system also supports JSON data structures for your data model. This makes it easy to work with and display data from REST APIs.

How do I know which list item is clicked on?

The SimpleRow::selected signal allows to handle click events on a list cell. For custom delegate items, you can add your own MouseArea for handling touch input.

 import VPlayApps 1.0

 App {
   NavigationStack {
     Page {
       title: "Clickable List Example"

       AppListView {
         delegate: SimpleRow {
           onSelected: console.log("Clicked Item #"+index+": "+JSON.stringify(modelData))
         }
         model: [
           {
             text: "Apple",
             detailText: "A delicious fruit with round shape",
             icon: IconType.apple
           },

           {
             text: "Beer",
             detailText: "A delicous drink",
             icon: IconType.beer
           }
         ]
       }
     }
   }
 }

How do I update ListViews dynamically?

The list view updates its UI automatically whenever the model changes - at least when you describe your model as a ListModel type. For plain JSON-based models, the list is not notified when some data values within the JSON structure change. In this case, you can manually trigger a property-changed signal, which in turn updates the UI of the list:

 import VPlayApps 1.0

 App {
   NavigationStack {
     Page {
       id: page
       title: "Append List Item Example"

       property var listData: [
           {
             text: "Apple",
             detailText: "A delicious fruit with round shape",
             icon: IconType.apple
           },

           {
             text: "Beer",
             detailText: "A delicous drink",
             icon: IconType.beer
           }
         ]

       AppListView {
         id: listView
         model: page.listData
         delegate: SimpleRow {
           onSelected: {
             page.listData.push(modelData) // add copy of clicked element at end of model
             page.listDataChanged() // signal change of data to update the list
           }
         }
       }
     }
   }
 }

More list examples are available here: Use ScrollViews and ListViews in Your App

Themes

How do I theme my app?

V-Play allows you to style your app with app-wide theme settings using the Theme component. This is in most cases more convenient than styling every single component itself. You can Style Your App with Themes for some simple theming examples.

The default Theme settings implement platform-specific styles, like Material Style for a native look and feel on Android. The following example shows how to manually change the used platform theme in your code:

 import VPlayApps 1.0

 App {

   Navigation {
     NavigationItem {
       title: "Main"
       icon: IconType.heart

       NavigationStack {
         Page {
           title: "Main Page"
           AppButton {
             text: "Switch Theme"
             onClicked: Theme.platform = (Theme.platform === "android") ? "ios" : "android"
             anchors.centerIn: parent

           }
         }
       }
     }

     NavigationItem {
       title: "Second"
       icon: IconType.thlarge

       NavigationStack {
         Page {  title: "Second Page" }
       }
     }
   }
 }

How do I set an app-wide custom font?

V-Play components make use of two different fonts, the Theme::normalFont and the Theme::boldFont. By default, these fonts match the platform's default font for V-Play Apps components.

If you want to explicitly provide your own font you can override the Theme properties with a FontLoader object:

 import VPlayApps 1.0
 import QtQuick 2.5

 App {

   // initialize theme with new font
   onInitTheme: {
     Theme.normalFont = arialFont
   }

   // load new font with FontLoader
   FontLoader {
     id: arialFont
     source: "../assets/fonts/Arial.ttf" // loaded from your assets folder
   }

   Page {
     // V-Play components like AppText automatically use the Theme fonts
     AppText {
       text: "I'm in Arial"
     }
   }
 }

Make sure to add your custom fonts to your app's assets and to provide the correct path in the FontLoader object. You can also use the custom font in your own app components, like the following example:

 Text {
   // Set reference to the global app font
   font.family: Theme.normalFont.name

   text: "Custom text item"
 }

Instead of replacing the general Theme font, you can also use a FontLoader and only overwrite the font.family property for certain text items.

How do I style my Text items?

Along with the font, you can customize many other styling properties of a Text item, such as:

  • color
  • elide
  • font.bold
  • font.capitalization
  • font.family
  • font.italic
  • font.letterSpacing
  • font.pixelSize
  • font.weight
  • font.wordSpacing
  • horizontalAlignment
  • lineHeight
  • maximumLineCount
  • verticalAlignment
  • wrapMode

Form input

What is the equivalent of a “hint” on an Input?

Input controls like AppTextInput or AppTextField own a placeHolderText property, which you can use for your hint text.

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Page {

     // remove focus from textedit if background is clicked
     MouseArea {
       anchors.fill: parent
       onClicked: textEdit.focus = false
     }

     // background for input
     Rectangle {
       anchors.fill: textEdit
       anchors.margins: -dp(8)
       color: "lightgrey"
     }

     // input
     AppTextInput {
       id: textEdit
       width: dp(200)
       placeholderText: "What's your name?"
       anchors.centerIn: parent
     }
   }
 }

How do I show validation errors?

The text input components provide predefined validators that you can use, they are called inputMethodHints.

You can also add custom validators to restrict the accepted input to a certain input type or expression. Input that does not match the validator is not accepted. To do custom validations and show errors for accepted input, you can add simple checks and control the visibility of errors with property bindings:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   // background for input
   Rectangle {
     anchors.fill: textInput
     anchors.margins: -dp(8)
     color: "lightgrey"
   }

   // input
   AppTextInput {
     id: textInput
     width: dp(200)
     placeholderText: "What's your name?"
     anchors.centerIn: parent

     // only allow letters and check length
     validator: RegExpValidator {
       regExp: /[A-Za-z]+/
     }
     property bool isTooLong: textInput.text.length >= 6
   }

   // show error if too long
   AppText {
     text: "Error: Use less than 6 letters."
     color: "red"
     anchors.top: textInput.bottom
     anchors.topMargin: dp(16)
     anchors.left: textInput.left
     visible: textInput.isTooLong
   }
 }

Native Utils and V-Play Plugins

How do I access GPS or other device sensors?

V-Play allows you to access various device sensors, with the Qt Sensors QML Types. The components for Positioning, Maps and Navigation are found in the Qt Positioning and Qt Location modules.

For an easy and convenient way to show a map with the current user position, you can also rely on the AppMap type:

 import VPlayApps 1.0
 import QtLocation 5.5
 import QtQuick 2.5

 App {
   // show the map
   AppMap {
     anchors.fill: parent

     // configure map provider
     plugin: Plugin {
       name: "mapbox"
       // configure your own map_id and access_token here
       parameters: [  PluginParameter {
           name: "mapbox.mapping.map_id"
           value: "mapbox.streets"
         },
         PluginParameter {
           name: "mapbox.access_token"
           value: "pk.eyJ1IjoiZ3R2cGxheSIsImEiOiJjaWZ0Y2pkM2cwMXZqdWVsenJhcGZ3ZDl5In0.6xMVtyc0CkYNYup76iMVNQ"
         },
         PluginParameter {
           name: "mapbox.mapping.highdpi_tiles"
           value: true
         }]
     }

     // configure the map to try to display the user's position
     showUserPosition: true
     zoomLevel: 13

     // check for user position initially when the component is created
     Component.onCompleted: {
       if(userPositionAvailable)
         center = userPosition.coordinate
     }

     // once we successfully received the location, we zoom to the user position
     onUserPositionAvailableChanged: {
       if(userPositionAvailable)
         zoomToUserPosition()
     }
   }
 }

How do I access the camera?

The V-Play NativeUtils allow to conveniently trigger native device features from within your QML code. For example to show dialogs, open the camera, access the gallery or work with contacts.

This simple example allows to take a photo with the device camera:

 import VPlayApps 1.0
 import QtQuick 2.0
 import QtMultimedia 5.9

 App {
   AppImage {
     id: image
     anchors.fill: parent
     fillMode: AppImage.PreserveAspectFit
     autoTransform: true
   }

   AppButton {
     text: "Take Photo"
     anchors.centerIn: parent
     onClicked: nativeUtils.displayCameraPicker("Take Photo")
   }

   Connections {
     target: nativeUtils
     onCameraPickerFinished: {
       image.source = ""
       if(accepted) {
         image.source = path
       }
     }
   }
 }

To embed a camera view directly in your app, you can use the Camera and VideoOutput types:

 import VPlayApps 1.0
 import QtQuick 2.0
 import QtMultimedia 5.9

 App {
   Camera {
     id: camera
   }

   VideoOutput {
     anchors.fill: parent
     source: camera
     autoOrientation: true
     fillMode: VideoOutput.PreserveAspectCrop
   }
 }

How do I set up push notifications?

V-Play supports both server-triggered and local notifications with V-Play Plugins. All plugins offer a platform-agnostic API and rely on native frameworks for each platform.

See the GoogleCloudMessaging Plugin or the OneSignal Plugin to add server-triggered notifications. Local notifications are available with the Notification Plugin. The following example schedules a notification to be fired after 5 seconds and trigger the notificationFired signal. You can also try to put the app in the background, to get the notification on your home screen. In this case, the notificationFired signal will be called when you enter the app after clicking on the notification.

 import QtQuick 2.1
 import VPlayApps 1.0
 import VPlayPlugins 1.0

 App {
   NotificationManager {
     id: notificationManager
     onNotificationFired: {
       nativeUtils.displayMessageBox("Notification", "id: "+notificationId, 1)
     }
   }

   Notification {
     id: idleNotification
     notificationId: "idleNotification"
     message: "Anyone here? Haven't seen you in a while..."
     timeInterval: 5 // in seconds
   }

   AppButton {
     text: "Schedule Notification (5s)"
     anchors.centerIn: parent
     onClicked: {
       // Cancel old notification if scheduled
       notificationManager.cancelNotification(idleNotification.notificationId)
       // Schedule idleNotification
       notificationManager.scheduleNotification(idleNotification)
     }
   }
 }

How do I log in with Facebook?

V-Play allows integrating Facebook with the Facebook Plugin. See the plugin documentation for more information and detailed integration steps.

Once set up, the plugin also integrates seamlessly with the V-Play Game Network service. Users that connect via Facebook will have the same user data synced across all their devices. To store custom data that you want to synchronize this way, you can use the WebStorage type.

How do I use Firebase features?

The Firebase Plugin is the right tool for integrating Firebase Authentication, Real-time Database or Cloud Storage features. See the plugin page for more information and detailed integration steps.

The Firebase Plugin has seen lots of improvements and new features lately. In case you are missing anything or run into issues, don't hesitate to get in touch!

How do I build my own custom native integrations?

In V-Play you code with QML, so going native first means to step into the Qt C++ world. You can find a guide how to mix V-Play QML code with Qt C++ components here: How to Expose a Qt C++ Class with Signals and Slots to QML

The demo is also available with the V-Play SDK: <Path to V-Play>/Examples/V-Play/appdemos/cpp-qml-integration

Working with your native Android code from C++ then requires JNI as the bridge between the two languages. Weaving in native iOS code is a little easier, as Objective-C is directly compatible with C++. But before you dive in too deep: Our developers are experts at building such native integrations, and we're happy to add features or build extensions as part of our support package offering!

Databases and local storage

How do I access Shared Preferences?

The App::settings property allows to store simple key/value pairs in a local database. If you format the value as a JSON string, you can also store more complex data in a very easy way.

 import VPlayApps 1.0
 import QtQuick 2.5

 App {
   id: app
   // this property holds how often the app was started
   property int numberAppStarts

   Component.onCompleted: {
     // getValue() returns undefined, if no setting for this key is found, so when this is the first start of the app
     numberAppStarts = app.settings.getValue("numberAppStarts") || 0 // defaults to '0' if 'undefined' is returned
     numberAppStarts++

     app.settings.setValue("numberAppStarts", numberAppStarts)
   }

   NavigationStack {

     Page {
       title: "Settings"

       AppText {
         anchors.centerIn: parent
         text: "App starts: " + numberAppStarts
       }
     }
   }
 }

The App settings in the above example internally rely on the Storage component. You can also add your own Storage to save your key-value pairs to a distinct database. Use the WebStorage to synchronize app data across multiple user devices with the V-Play Game Network service. You can find more info on storage, data and Firebase here: Store Data Persistent

How do I access SQLite in V-Play?

You can access a local SQLite Database using the Qt Quick Local Storage QML Types.

More App Use-Case Examples

In the documentation navigation on the left-hand side, you can find tons of useful examples grouped into the main use-cases for app developers. Make sure to check them out!

Voted #1 for:

  • Easiest to learn
  • Most time saving
  • Best support

Develop Cross-Platform Apps and Games 50% Faster!

  • Voted the best supported, most time-saving and easiest to learn cross-platform development tool
  • Based on the Qt framework, with native performance and appearance on all platforms including iOS and Android
  • Offers a variety of plugins to monetize, analyze and engage users
FREE!
create apps
create games
cross platform
native performance
3rd party services
game network
multiplayer
level editor
easiest to learn
biggest time saving
best support