Qt Bubble Level Example

Files:

Qt Bubble Level is a simple application that uses Qt Mobility's accelerometer APIs and hardware sensor information to calculate the inclination of the device and presents this as atraditional bubble level. The application provides a calibration feature to handle any possible errors in accelerometer readings. The example is hosted in Projects Forum Nokia: https://projects.forum.nokia.com/qtbubblelevel

Note: This demonstration requires QtMobility libraries.

Initialising the application

All of the initialisations are done in the main function.

First, QDeclarativeView is created to intepret the QML files. The QML file given is found in the Qt resource. The root QML element is set to resize to the view whenever the view is resized.

  1.                 QDeclarativeView view;
  2. view.setSource(QUrl("qrc:/qml/BubbleLevel.qml"));
  3. view.setResizeMode(QDeclarativeView::SizeRootObjectToView);

The Settings object will handle the loading or storing of the calibration value. Next, we create instances from QAccelerometer and AccelerometerFilter and attach the filter to the sensor.

  1. Settings settings;
  2.  
  3. QAccelerometer sensor;
  4. AccelerometerFilter filter;
  5. sensor.addFilter(&filter);

The Qt code is then connected to QML code by using Qt Signals and Slots connections. First, the root object is retrieved from QDeclarativeView. The root object now represents the Qt object of the QML root element.

The saveCorrectionAngle signal of the QML root element is connected to the Qt slot saveCorrectionAngle. The rotationChanged and correctionAngle Qt signals are connected to the handleRotation and setCorrectionAngle slot of the QML root element. Finally, the quit signal of QDeclarativeEngine is connected to QApplication's quit slot.

  1.                 QObject *rootObject = dynamic_cast<QObject*>(view.rootObject());
  2.  
  3. // Associate Qt / QML signals and slots
  4. QObject::connect(rootObject, SIGNAL(saveCorrectionAngle(const QVariant&)),
  5.                  &settings, SLOT(saveCorrectionAngle(const QVariant&)));
  6.  
  7. QObject::connect(&filter, SIGNAL(rotationChanged(const QVariant&)),
  8.                  rootObject, SLOT(handleRotation(const QVariant&)));
  9.  
  10. QObject::connect(&settings, SIGNAL(correctionAngle(const QVariant&)),
  11.                  rootObject, SLOT(setCorrectionAngle(const QVariant&)));
  12.  
  13. QObject::connect((QObject*)view.engine(), SIGNAL(quit()),
  14.                  &app, SLOT(quit()));

On the Maemo target, the application needs a minimise button, so we connect one additional QML signal to the Qt slot. The minimise button is made visible by setting the value of the QML root element's taskSwitcherVisible property to true.

  1. #ifdef Q_WS_MAEMO_5
  2. TaskSwitcher taskSwitcher;
  3.  
  4. QObject::connect(rootObject, SIGNAL(minimizeApplication()),
  5.                  &taskSwitcher, SLOT(minimizeApplication()));
  6.  
  7. // Show the task switcher button
  8. rootObject->setProperty("taskSwitcherVisible", true);
  9. #endif

The correction factor of the accelerometer is retrieved from persistent storage by using QSettings. The correction factor is signalled to the QML side by using the function setCorrectionAngle. The accelerometer sensor is started and it will eventually begin to signal the changes in accelerometer readings.

  1. // Read correction factor from permanent storage and emit it to QML side
  2. settings.loadAndEmitCorrectionAngle();
  3.  
  4. // Begin measuring of the accelerometer sensor
  5. sensor.start();

Finally, in the end of the function the view is shown in full screen on mobile devices. On other targets, the application is shown as 800 x 480 resolution in the 100, 100 position from the top-left corner of the desktop.

  1. #if defined(Q_WS_MAEMO_5) || defined(Q_OS_SYMBIAN) || defined(Q_WS_SIMULATOR)
  2. view.setGeometry(QApplication::desktop()->screenGeometry());
  3. view.showFullScreen();
  4. #else
  5. view.setGeometry((QRect(100, 100, 800, 480)));
  6. view.show();
  7. #endif

Accessing the accelerometer information

The inclination of the device is resolved by using the QAccelerometer sensor of QtMobility. We already created the sensor in the main function and attached our self-derived AccelerometerFilter object to it. Here is the definition of the AccelerometerFilter class:

  1. #include <QAccelerometerFilter>
  2. #include <QVariant>
  3.  
  4. QTM_USE_NAMESPACE
  5.  
  6. class AccelerometerFilter
  7.     : public QObject, public QAccelerometerFilter
  8.  {
  9.     Q_OBJECT
  10.  
  11. protected:
  12.     qreal x;
  13.     qreal y;
  14.     qreal z;
  15.  
  16. public:
  17.     AccelerometerFilter();
  18.     bool filter(QAccelerometerReading *reading);
  19.  
  20. signals:
  21.     void rotationChanged(const QVariant &deg);
  22. };

The class is multiderived from QObject and QAccelerometerFilter classes. The QAccelerometerFilter class is derived from QObject because we want to use Qt Signals and Slots to signal changes in accelerometer readings.

The members x, y, and z store the previous values of the sensor reading in order to implement a low pass filter to the values.

In the implementation of the AccelerometerFilter class, we first read the value of each axis from the QAccelerometerReading object. The values are then converted from radians to degrees and applied the low pass filter to reduce noise in the sensor readings. Different low pass factors are used depending on the platform (these were determined to be good via experimenting). Finally, the calculated value is emitted.

Note that the accelerometer sensors are oriented differently in Symbian and Maemo devices, and we must account for this by using platform-specific code.

  1. bool AccelerometerFilter::filter(QAccelerometerReading *reading)
  2.  {
  3.     qreal rx = reading->x();
  4.     qreal ry = reading->y();
  5.     qreal rz = reading->z();
  6.  
  7.     qreal divider = sqrt(rx * rx + ry * ry + rz * rz);
  8.  
  9.     // Lowpass factor
  10. #ifdef Q_OS_SYMBIAN
  11.     float lowPassFactor = 0.10;
  12. #else
  13.     float lowPassFactor = 0.05;
  14. #endif
  15.  
  16.     // Calculate the axis angles in degrees and reduce the noise in sensor
  17.     // readings.
  18.     x += (acos(rx / divider) * RADIANS_TO_DEGREES - 90 - x) * lowPassFactor;
  19.     y += (acos(ry / divider) * RADIANS_TO_DEGREES - 90 - y) * lowPassFactor;
  20.     z += (acos(rz / divider) * RADIANS_TO_DEGREES - 90 - z) * lowPassFactor;
  21.  
  22.     // The orientations of the accelerometers are different between
  23.     // Symbian and Maemo devices so we use the different axes
  24.     // depending on the platform.
  25. #if defined(Q_OS_SYMBIAN)
  26.     emit rotationChanged(-y);
  27. #else
  28.     emit rotationChanged(x);
  29. #endif
  30.  
  31.     // Don't store the reading in the sensor.
  32.     return false;
  33. }

The Qt Quick UI

BubbleLevel.qml is the main QML element. It represents the wooden board of the bubble level, and it also acts as a connection point between the QML and the Qt side. In the beginning of the element, there are two signals, two functions, and one property. All of these define the interface between Qt and QML.

On the Maemo platform, when the application is to be minimised, minimizeApplication is signalled. When a new calibration factor is to be stored in the device's memory, saveCorrectionAngle is signalled.

The handleRotation function acts as a Qt slot to which the AccelerometerFilters signal rotationChanged is connected. Similarly, the setCorrectionAngle function also acts as a Qt slot to which the Settings object's signal, correctionAngle, is connected.

The property alias taskSwitcherVisible is provided to allow the Qt model to show or hide the task switcher button which minimises the application. This is only meaningful on Maemo platforms, where every application normally has a task switcher button.

  1. // Signaled when task switcher button is pressed
  2. signal minimizeApplication()
  3.  
  4. // Signaled when correction angle is saved
  5. signal saveCorrectionAngle(variant angle)
  6.  
  7. // These functions are used as Qt slots
  8. function handleRotation(deg)  {
  9.     horTube.rawangle = deg
  10. }
  11.  
  12. function setCorrectionAngle(deg)  {
  13.     horTube.angleconstant = deg
  14. }
  15.  
  16. // Used to show the task switcher button in Maemo targets
  17. property alias taskSwitcherVisible: taskSwitcher.visible

The Tube element represents the the glass tube of the bubble level. It is anchored to the centre of the wooden board. The width and height are calculated with specific factors to make the glass tube scale to different resolutions.

  1. Tube  {
  2.     id: horTube
  3.  
  4.     property real rawangle: 0
  5.     property real angleconstant: 0
  6.  
  7.     anchors.horizontalCenter: parent.horizontalCenter
  8.     width: parent.width * 0.775; height: parent.height * 0.15625
  9.     deg: rawangle - angleconstant
  10. }

In the implementation of Tube.qml, the property deg represents the current inclination. The x-position of the bubble is bound to the JavaScript function calX which is called every time the property deg, center, or bubblCenter is changed. The function places the bubble in the corresponding place on its parent.

  1.                 Item  {
  2.     id: tube
  3.  
  4.     property real deg
  5.  
  6.     Image  {
  7.         id: bubble
  8.  
  9.         property real center: tube.width / 2
  10.         property real bubbleCenter: bubble.width / 2
  11.  
  12.         function calX()  {
  13.             var newX = center + tube.deg / -20 * center
  14.  
  15.             if((newX - bubbleCenter) < 0)  {
  16.                 return 0
  17.             }
  18.             else if((newX + bubbleCenter) > tube.width)  {
  19.                 return tube.width - 2 * bubbleCenter
  20.             }
  21.  
  22.             return newX - bubbleCenter;
  23.         }
  24.  
  25.         x: calX()
  26.         width: 0.16129032 * parent.width; height: 0.66666667 * parent.height
  27.         source: "images/bubble.png"
  28.         smooth: true
  29.     }
  30.  
  31.     Image  {
  32.         anchors.horizontalCenter: parent.horizontalCenter
  33.         width: 0.36451613 * parent.width; height: 0.66666667 * parent.height
  34.         source: "images/scale.png"
  35.     }
  36.  
  37.     Image  {
  38.         width: parent.width; height:  0.32 * parent.height
  39.         opacity: 0.8
  40.         source: "images/reflection.png"
  41.     }
  42. }
Notes provided by the Qt Community

No notes