Busy Indicator for QML: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Redirected page to Busy-Indicator-for-QML)
(Copied content from other location to here)
Line 1: Line 1:
#REDIRECT [[Busy-Indicator-for-QML]]
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}
 
[[Category:Snippets]]
[[Category:HowTo]]
[[Category:Developing_with_Qt::Qt Quick]]
[[Category:Developing_with_Qt::Qt Quick::QML]]
 
'''English''' | [[Busy-Indicator-for-QML_German|Deutsch]]
 
= Busy Indicator =
 
== Introduction ==
 
'''QtQuick.Controls 1.3''' come with the '''BusyIndicator'''. It is a simple and ready to use component. Here is a short example for how to use it:
 
<code>
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
 
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
 
BusyIndicator {
id: busyIndication
anchors.centerIn: parent
// 'running' defaults to 'true'
}
 
Button {
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
text: busyIndication.running ? "Stop Busy Indicator" : "Start Busy Indicator"
checkable: true
checked: busyIndication.running
onClicked: busyIndication.running = !busyIndication.running
}
}
</code>
 
'''The following describes the implementation of a custom busy indicator for QtQuick 1.'''
 
Certain graphical assets may take a while to load or you may wish to show that some other processing is going on. This custom BusyIndicator shows one way in which visual feedback can be provided. This busy indicator has been implemented as a custom QDeclarativeItem in C++ since it uses a conical gradient which it is not possible to represent in an SVG (which only have support for linear and radial gradients). We do take care to minimise the amount of expensive imperative drawing operations. My inspiration for this design comes from StarCraft 2 ;-)
 
http://gallery.theharmers.co.uk/upload/2011/04/30/20110430160839-0a540a36.png
 
==Implementation==
 
First, here is the class declaration:
 
<code>
#ifndef BUSYINDICATOR_H
#define BUSYINDICATOR_H
 
#include <QDeclarativeItem>
 
class BusyIndicator : public QDeclarativeItem
{
Q_OBJECT
Q_PROPERTY( qreal innerRadius READ innerRadius WRITE setInnerRadius NOTIFY innerRadiusChanged )
Q_PROPERTY( qreal outerRadius READ outerRadius WRITE setOuterRadius NOTIFY outerRadiusChanged )
Q_PROPERTY( QColor backgroundColor READ backgroundColor WRITE setBackgroundColor NOTIFY backgroundColorChanged )
Q_PROPERTY( QColor foregroundColor READ foregroundColor WRITE setForegroundColor NOTIFY foregroundColorChanged )
Q_PROPERTY( qreal actualInnerRadius READ actualInnerRadius NOTIFY actualInnerRadiusChanged )
Q_PROPERTY( qreal actualOuterRadius READ actualOuterRadius NOTIFY actualOuterRadiusChanged )
 
public:
explicit BusyIndicator( QDeclarativeItem* parent = 0 );
 
void setInnerRadius( const qreal& innerRadius );
qreal innerRadius() const;
 
void setOuterRadius( const qreal& outerRadius );
qreal outerRadius() const;
 
void setBackgroundColor( const QColor& color );
QColor backgroundColor() const;
 
void setForegroundColor( const QColor& color );
QColor foregroundColor() const;
 
qreal actualInnerRadius() const;
qreal actualOuterRadius() const;
 
virtual void paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0 );
 
signals:
void innerRadiusChanged();
void outerRadiusChanged();
void backgroundColorChanged();
void foregroundColorChanged();
void actualInnerRadiusChanged();
void actualOuterRadiusChanged();
 
protected slots:
virtual void updateSpinner();
 
private:
// User settable properties
qreal m_innerRadius; // In range (0, m_outerRadius]
qreal m_outerRadius; // (m_innerRadius, 1]
QColor m_backgroundColor;
QColor m_foregroundColor;
 
// The calculated size, inner and outer radii
qreal m_size;
qreal m_actualInnerRadius;
qreal m_actualOuterRadius;
 
QString m_cacheKey;
};
 
#endif // BUSYINDICATOR_H
</code>
 
This is quite a simple sub-class of QDeclarativeItem with only a handful of properties for setting the inner and outer radii of the busy indicator's ring as a fraction of the item's size. In this case the item's size is defined to be min( width, height ) so as to preserve the 1:1 aspect ratio of the ring.
 
Now for the implementation:
 
<code>
#include "busyindicator.h"
 
#include <QConicalGradient>
#include <QPainter>
#include <QPainterPath>
#include <QPixmapCache>
 
BusyIndicator::BusyIndicator( QDeclarativeItem* parent )
: QDeclarativeItem( parent ),
m_innerRadius( 0.8 ),
m_outerRadius( 1.0 ),
m_backgroundColor( 177, 210, 143, 70 ),
m_foregroundColor( 119, 183, 83, 255 ),
m_actualInnerRadius( 90.0 ),
m_actualOuterRadius( 100.0 ),
m_cacheKey()
{
setFlag( QGraphicsItem::ItemHasNoContents, false );
setWidth( 100.0 );
setHeight( 100.0 );
 
updateSpinner();
 
connect( this, SIGNAL( widthChanged() ), SLOT( updateSpinner() ) );
connect( this, SIGNAL( heightChanged() ), SLOT( updateSpinner() ) );
}
 
void BusyIndicator::setInnerRadius( const qreal& innerRadius )
{
if ( qFuzzyCompare( m_innerRadius, innerRadius ) )
return;
m_innerRadius = innerRadius;
updateSpinner();
emit innerRadiusChanged();
}
 
qreal BusyIndicator::innerRadius() const
{
return m_innerRadius;
}
 
void BusyIndicator::setOuterRadius( const qreal& outerRadius )
{
if ( qFuzzyCompare( m_outerRadius, outerRadius ) )
return;
m_outerRadius = outerRadius;
updateSpinner();
emit outerRadiusChanged();
}
 
qreal BusyIndicator::outerRadius() const
{
return m_outerRadius;
}
 
void BusyIndicator::setBackgroundColor( const QColor& color )
{
if ( m_backgroundColor == color )
return;
m_backgroundColor = color;
updateSpinner();
emit backgroundColorChanged();
}
 
QColor BusyIndicator::backgroundColor() const
{
return m_backgroundColor;
}
 
void BusyIndicator::setForegroundColor( const QColor& color )
{
if ( m_foregroundColor == color )
return;
m_foregroundColor = color;
updateSpinner();
emit foregroundColorChanged();
}
 
QColor BusyIndicator::foregroundColor() const
{
return m_foregroundColor;
}
 
qreal BusyIndicator::actualInnerRadius() const
{
return m_actualInnerRadius;
}
 
qreal BusyIndicator::actualOuterRadius() const
{
return m_actualOuterRadius;
}
 
void BusyIndicator::updateSpinner()
{
// Calculate new inner and outer radii
m_size = qMin( width(), height() );
qreal nCoef = 0.5 * m_size;
m_actualInnerRadius = nCoef * m_innerRadius;
m_actualOuterRadius = nCoef * m_outerRadius;
 
// Calculate a new key
m_cacheKey = m_backgroundColor.name();
m_cacheKey ''= "-";
m_cacheKey ''= m_foregroundColor.name();
m_cacheKey''= "-";
m_cacheKey''= QString::number(m_actualOuterRadius);
m_cacheKey += "-";
m_cacheKey ''= QString::number(m_actualInnerRadius);
 
emit actualInnerRadiusChanged();
emit actualOuterRadiusChanged();
}
 
void BusyIndicator::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget )
{
Q_UNUSED( option );
Q_UNUSED( widget );
 
QPixmap pixmap;
if ( !QPixmapCache::find( m_cacheKey, pixmap ) )
{
// Set up a convenient path
QPainterPath path;
path.setFillRule( Qt::OddEvenFill );
path.addEllipse( QPointF( m_actualOuterRadius, m_actualOuterRadius ), m_actualOuterRadius, m_actualOuterRadius );
path.addEllipse( QPointF( m_actualOuterRadius, m_actualOuterRadius ), m_actualInnerRadius, m_actualInnerRadius );
 
qreal nActualDiameter = 2 * m_actualOuterRadius;
pixmap = QPixmap( nActualDiameter, nActualDiameter );
pixmap.fill( Qt::transparent );
QPainter p( &pixmap );
 
// Draw the ring background
p.setPen( Qt::NoPen );
p.setBrush( m_backgroundColor );
p.setRenderHint( QPainter::Antialiasing );
p.drawPath( path );
 
// Draw the ring foreground
QConicalGradient gradient( QPointF( m_actualOuterRadius, m_actualOuterRadius ), 0.0 );
gradient.setColorAt( 0.0, Qt::transparent );
gradient.setColorAt( 0.05, m_foregroundColor );
gradient.setColorAt( 0.8, Qt::transparent );
p.setBrush( gradient );
p.drawPath( path );
p.end();
 
QPixmapCache::insert( m_cacheKey, pixmap );
}
 
// Draw pixmap at center of item
painter->drawPixmap( 0.5 * ( width() - m_size ), 0.5 * ( height() - m_size ), pixmap );
}
</code>
 
In the constructor we set up a default size of 100x100 pixels for the indicator and call the updateSpinner() function. This function is also called whenever one of the affecting properties changes. These are:
 
* Height
* Width
* Inner radius
* Outer radius
* Background color
* Foreground color
 
The implementation of the updateSpinner() function only calculates a new QString value which is later used in paint() as a key in the global QPixmapCache. In the paint() function we check to see if the QPixmapCache already contains a matching pixmap or not. If it does we paint it. If it does not we first generate it, store it in the cache and then paint it.
 
This approach minimises the amount of expensive painting calls and key constructions.
 
==Usage==
 
Before we can use our custom item in any QML scene we need to expose it to the QML world. We do this with something along these lines:
 
<code>
qmlRegisterType<BusyIndicator>( "ZapBsComponents", 1, 0, "BusyIndicator" );
</code>
 
Then in your QML scene you need to instruct the QML backend to import this collection (of 1) components with:
 
<code>
import ZapBsComponents 1.0
</code>
 
You are now ready to roll.
 
===Independent Usage===
 
<code>
import QtQuick 1.0
import ZapBsComponents 1.0
 
Rectangle {
id: root
width: 640
height: 360
 
// Trying out the new BusyIndicator custom item
BusyIndicator {
id: busy1
anchors.centerIn: parent
 
// Make the ring do something interesting
RotationAnimation
{
target: busy1
property: "rotation" // Suppress a warning
from: 0
to: 360
direction: RotationAnimation.Clockwise
duration: 1000
loops: Animation.Infinite
running: true
}
}
}
</code>
 
The above should provide you with a nicely spinning busy indicator. Obviously the size and colors can be varied using the properties we declared in the header file.
 
===Compound Usage Within Another Component===
 
It is also easy to include the BusyIndicator into compound components. One example might be for slow to load images:
 
<code>
import QtQuick 1.0
import ZapBsComponents 1.0
 
Item {
id: container
property alias source: image.source
property alias fillMode: image.fillMode
 
Image {
id: image
anchors.fill: parent
}
 
BusyIndicator {
id: busyIndicator
anchors.fill: parent
visible: image.status != Image.Ready
 
RotationAnimation
{
target: busyIndicator
property: "rotation" // Suppress a warning
from: 0
to: 360
direction: RotationAnimation.Clockwise
duration: 1000
loops: Animation.Infinite
running: image.status != Image.Ready
}
}
}
</code>
 
This will show a nice spinning busy indicator until the image is loaded. Of course you can expose more of the properties to the outside world if you like - this is just a simple example after all.
 
Another example using this Busy Indicator component along with a small progress bar in the center of the spinning ring to show loading progress for e.g. is shown in this [http://developer.qt.nokia.com/wiki/QML_Progress_Spinner snippet].
 
===Independent Usage as Widget===
 
This implementation of a busy indicator can also be used without QML. It can be added as widget through [http://developer.qt.nokia.com/doc/qt-4.7/qgraphicsview.html QGraphicsView] and [http://developer.qt.nokia.com/doc/qt-4.7/qgraphicsscene.html QGraphicsScene] to a [http://developer.qt.nokia.com/doc/qt-4.7/qlayout.html layout] and animated with [http://developer.qt.nokia.com/doc/qt-4.7/qtimeline.html QTimeLine] as shown at the following example. It is important to note that the viewport must be set in order to display the busy indicator.
 
====Example====
 
* pro file
 
<code>QT''= declarative</code>
 
* mainwindow.h
<code>
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include "busyindicator.h"
 
#include <QGraphicsScene>
#include <QTimeLine>
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
enum ScreenOrientation {
ScreenOrientationLockPortrait,
ScreenOrientationLockLandscape,
ScreenOrientationAuto
};
 
explicit MainWindow(QWidget '''parent = 0);
virtual ~MainWindow();
 
private slots:
 
void rotateSpinner(int nValue);
 
private:
 
BusyIndicator''' m_pBusyIndicator;
 
QGraphicsScene* m_scene;
 
QTimeLine* m_pTimeLine;
 
};
 
#endif // MAINWINDOW_H
 
</code>
 
* mainwindow.cpp
<code>
#include "mainwindow.h"
 
#include <QCoreApplication>
 
#include <QGraphicsView>
#include <QVBoxLayout>
 
MainWindow::MainWindow(QWidget '''parent)
: QMainWindow(parent), m_pBusyIndicator(NULL), m_pTimeLine(NULL)
{
QLayout''' pLayout = new QVBoxLayout();
 
QGraphicsScene* pScene = new QGraphicsScene(this);
m_pBusyIndicator = new BusyIndicator();
pScene->addItem(dynamic_cast<QGraphicsItem*>(m_pBusyIndicator));
 
QGraphicsView* pView = new QGraphicsView(pScene, this);
pView->setViewport(this);
pView->setMinimumHeight(200);
pView->show();
 
pLayout->addWidget(pView);
setLayout(pLayout);
 
m_pTimeLine = new QTimeLine(1000, this);
m_pTimeLine->setLoopCount(0);
m_pTimeLine->setFrameRange(0, 36);
 
connect(m_pTimeLine, SIGNAL (frameChanged(int)), this, SLOT (rotateSpinner(int)));
m_pTimeLine->start();
 
}
//——————————————————————————
 
MainWindow::~MainWindow()
{
//Nothing to do
}
//——————————————————————————
 
void MainWindow::rotateSpinner(int nValue)
{
qreal nTransX = m_pBusyIndicator->actualOuterRadius();
m_pBusyIndicator->setTransform(QTransform().translate(nTransX, nTransX).
rotate(nValue*10).translate(–1*nTransX, –1*nTransX));
}
//——————————————————————————
 
</code>

Revision as of 10:29, 28 June 2015

This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

English | Deutsch

Busy Indicator

Introduction

QtQuick.Controls 1.3 come with the BusyIndicator. It is a simple and ready to use component. Here is a short example for how to use it:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2

ApplicationWindow {
 title: qsTr("Hello World")
 width: 640
 height: 480
 visible: true

BusyIndicator {
 id: busyIndication
 anchors.centerIn: parent
 // 'running' defaults to 'true'
 }

Button {
 anchors.horizontalCenter: parent.horizontalCenter
 anchors.bottom: parent.bottom
 text: busyIndication.running ? "Stop Busy Indicator" : "Start Busy Indicator"
 checkable: true
 checked: busyIndication.running
 onClicked: busyIndication.running = !busyIndication.running
 }
}

The following describes the implementation of a custom busy indicator for QtQuick 1.

Certain graphical assets may take a while to load or you may wish to show that some other processing is going on. This custom BusyIndicator shows one way in which visual feedback can be provided. This busy indicator has been implemented as a custom QDeclarativeItem in C++ since it uses a conical gradient which it is not possible to represent in an SVG (which only have support for linear and radial gradients). We do take care to minimise the amount of expensive imperative drawing operations. My inspiration for this design comes from StarCraft 2 ;-)

20110430160839-0a540a36.png

Implementation

First, here is the class declaration:

#ifndef BUSYINDICATOR_H
#define BUSYINDICATOR_H

#include <QDeclarativeItem>

class BusyIndicator : public QDeclarativeItem
{
 Q_OBJECT
 Q_PROPERTY( qreal innerRadius READ innerRadius WRITE setInnerRadius NOTIFY innerRadiusChanged )
 Q_PROPERTY( qreal outerRadius READ outerRadius WRITE setOuterRadius NOTIFY outerRadiusChanged )
 Q_PROPERTY( QColor backgroundColor READ backgroundColor WRITE setBackgroundColor NOTIFY backgroundColorChanged )
 Q_PROPERTY( QColor foregroundColor READ foregroundColor WRITE setForegroundColor NOTIFY foregroundColorChanged )
 Q_PROPERTY( qreal actualInnerRadius READ actualInnerRadius NOTIFY actualInnerRadiusChanged )
 Q_PROPERTY( qreal actualOuterRadius READ actualOuterRadius NOTIFY actualOuterRadiusChanged )

public:
 explicit BusyIndicator( QDeclarativeItem* parent = 0 );

 void setInnerRadius( const qreal& innerRadius );
 qreal innerRadius() const;

 void setOuterRadius( const qreal& outerRadius );
 qreal outerRadius() const;

 void setBackgroundColor( const QColor& color );
 QColor backgroundColor() const;

 void setForegroundColor( const QColor& color );
 QColor foregroundColor() const;

 qreal actualInnerRadius() const;
 qreal actualOuterRadius() const;

 virtual void paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0 );

signals:
 void innerRadiusChanged();
 void outerRadiusChanged();
 void backgroundColorChanged();
 void foregroundColorChanged();
 void actualInnerRadiusChanged();
 void actualOuterRadiusChanged();

protected slots:
 virtual void updateSpinner();

private:
 // User settable properties
 qreal m_innerRadius; // In range (0, m_outerRadius]
 qreal m_outerRadius; // (m_innerRadius, 1]
 QColor m_backgroundColor;
 QColor m_foregroundColor;

 // The calculated size, inner and outer radii
 qreal m_size;
 qreal m_actualInnerRadius;
 qreal m_actualOuterRadius;

 QString m_cacheKey;
};

#endif // BUSYINDICATOR_H

This is quite a simple sub-class of QDeclarativeItem with only a handful of properties for setting the inner and outer radii of the busy indicator's ring as a fraction of the item's size. In this case the item's size is defined to be min( width, height ) so as to preserve the 1:1 aspect ratio of the ring.

Now for the implementation:

#include "busyindicator.h"

#include <QConicalGradient>
#include <QPainter>
#include <QPainterPath>
#include <QPixmapCache>

BusyIndicator::BusyIndicator( QDeclarativeItem* parent )
 : QDeclarativeItem( parent ),
 m_innerRadius( 0.8 ),
 m_outerRadius( 1.0 ),
 m_backgroundColor( 177, 210, 143, 70 ),
 m_foregroundColor( 119, 183, 83, 255 ),
 m_actualInnerRadius( 90.0 ),
 m_actualOuterRadius( 100.0 ),
 m_cacheKey()
{
 setFlag( QGraphicsItem::ItemHasNoContents, false );
 setWidth( 100.0 );
 setHeight( 100.0 );

 updateSpinner();

 connect( this, SIGNAL( widthChanged() ), SLOT( updateSpinner() ) );
 connect( this, SIGNAL( heightChanged() ), SLOT( updateSpinner() ) );
}

void BusyIndicator::setInnerRadius( const qreal& innerRadius )
{
 if ( qFuzzyCompare( m_innerRadius, innerRadius ) )
 return;
 m_innerRadius = innerRadius;
 updateSpinner();
 emit innerRadiusChanged();
}

qreal BusyIndicator::innerRadius() const
{
 return m_innerRadius;
}

void BusyIndicator::setOuterRadius( const qreal& outerRadius )
{
 if ( qFuzzyCompare( m_outerRadius, outerRadius ) )
 return;
 m_outerRadius = outerRadius;
 updateSpinner();
 emit outerRadiusChanged();
}

qreal BusyIndicator::outerRadius() const
{
 return m_outerRadius;
}

void BusyIndicator::setBackgroundColor( const QColor& color )
{
 if ( m_backgroundColor == color )
 return;
 m_backgroundColor = color;
 updateSpinner();
 emit backgroundColorChanged();
}

QColor BusyIndicator::backgroundColor() const
{
 return m_backgroundColor;
}

void BusyIndicator::setForegroundColor( const QColor& color )
{
 if ( m_foregroundColor == color )
 return;
 m_foregroundColor = color;
 updateSpinner();
 emit foregroundColorChanged();
}

QColor BusyIndicator::foregroundColor() const
{
 return m_foregroundColor;
}

qreal BusyIndicator::actualInnerRadius() const
{
 return m_actualInnerRadius;
}

qreal BusyIndicator::actualOuterRadius() const
{
 return m_actualOuterRadius;
}

void BusyIndicator::updateSpinner()
{
 // Calculate new inner and outer radii
 m_size = qMin( width(), height() );
 qreal nCoef = 0.5 * m_size;
 m_actualInnerRadius = nCoef * m_innerRadius;
 m_actualOuterRadius = nCoef * m_outerRadius;

 // Calculate a new key
 m_cacheKey = m_backgroundColor.name();
 m_cacheKey ''= "-";
 m_cacheKey ''= m_foregroundColor.name();
 m_cacheKey''= "-";
 m_cacheKey''= QString::number(m_actualOuterRadius);
 m_cacheKey += "-";
 m_cacheKey ''= QString::number(m_actualInnerRadius);

 emit actualInnerRadiusChanged();
 emit actualOuterRadiusChanged();
}

void BusyIndicator::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget )
{
 Q_UNUSED( option );
 Q_UNUSED( widget );

 QPixmap pixmap;
 if ( !QPixmapCache::find( m_cacheKey, pixmap ) )
 {
 // Set up a convenient path
 QPainterPath path;
 path.setFillRule( Qt::OddEvenFill );
 path.addEllipse( QPointF( m_actualOuterRadius, m_actualOuterRadius ), m_actualOuterRadius, m_actualOuterRadius );
 path.addEllipse( QPointF( m_actualOuterRadius, m_actualOuterRadius ), m_actualInnerRadius, m_actualInnerRadius );

 qreal nActualDiameter = 2 * m_actualOuterRadius;
 pixmap = QPixmap( nActualDiameter, nActualDiameter );
 pixmap.fill( Qt::transparent );
 QPainter p( &pixmap );

 // Draw the ring background
 p.setPen( Qt::NoPen );
 p.setBrush( m_backgroundColor );
 p.setRenderHint( QPainter::Antialiasing );
 p.drawPath( path );

 // Draw the ring foreground
 QConicalGradient gradient( QPointF( m_actualOuterRadius, m_actualOuterRadius ), 0.0 );
 gradient.setColorAt( 0.0, Qt::transparent );
 gradient.setColorAt( 0.05, m_foregroundColor );
 gradient.setColorAt( 0.8, Qt::transparent );
 p.setBrush( gradient );
 p.drawPath( path );
 p.end();

 QPixmapCache::insert( m_cacheKey, pixmap );
 }

 // Draw pixmap at center of item
 painter->drawPixmap( 0.5 * ( width() - m_size ), 0.5 * ( height() - m_size ), pixmap );
}

In the constructor we set up a default size of 100x100 pixels for the indicator and call the updateSpinner() function. This function is also called whenever one of the affecting properties changes. These are:

  • Height
  • Width
  • Inner radius
  • Outer radius
  • Background color
  • Foreground color

The implementation of the updateSpinner() function only calculates a new QString value which is later used in paint() as a key in the global QPixmapCache. In the paint() function we check to see if the QPixmapCache already contains a matching pixmap or not. If it does we paint it. If it does not we first generate it, store it in the cache and then paint it.

This approach minimises the amount of expensive painting calls and key constructions.

Usage

Before we can use our custom item in any QML scene we need to expose it to the QML world. We do this with something along these lines:

qmlRegisterType<BusyIndicator>( "ZapBsComponents", 1, 0, "BusyIndicator" );

Then in your QML scene you need to instruct the QML backend to import this collection (of 1) components with:

import ZapBsComponents 1.0

You are now ready to roll.

Independent Usage

import QtQuick 1.0
import ZapBsComponents 1.0

Rectangle {
 id: root
 width: 640
 height: 360

 // Trying out the new BusyIndicator custom item
 BusyIndicator {
 id: busy1
 anchors.centerIn: parent

 // Make the ring do something interesting
 RotationAnimation
 {
 target: busy1
 property: "rotation" // Suppress a warning
 from: 0
 to: 360
 direction: RotationAnimation.Clockwise
 duration: 1000
 loops: Animation.Infinite
 running: true
 }
 }
}

The above should provide you with a nicely spinning busy indicator. Obviously the size and colors can be varied using the properties we declared in the header file.

Compound Usage Within Another Component

It is also easy to include the BusyIndicator into compound components. One example might be for slow to load images:

import QtQuick 1.0
import ZapBsComponents 1.0

Item {
 id: container
 property alias source: image.source
 property alias fillMode: image.fillMode

 Image {
 id: image
 anchors.fill: parent
 }

 BusyIndicator {
 id: busyIndicator
 anchors.fill: parent
 visible: image.status != Image.Ready

 RotationAnimation
 {
 target: busyIndicator
 property: "rotation" // Suppress a warning
 from: 0
 to: 360
 direction: RotationAnimation.Clockwise
 duration: 1000
 loops: Animation.Infinite
 running: image.status != Image.Ready
 }
 }
}

This will show a nice spinning busy indicator until the image is loaded. Of course you can expose more of the properties to the outside world if you like - this is just a simple example after all.

Another example using this Busy Indicator component along with a small progress bar in the center of the spinning ring to show loading progress for e.g. is shown in this snippet.

Independent Usage as Widget

This implementation of a busy indicator can also be used without QML. It can be added as widget through QGraphicsView and QGraphicsScene to a layout and animated with QTimeLine as shown at the following example. It is important to note that the viewport must be set in order to display the busy indicator.

Example

  • pro file
QT''= declarative
  • mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "busyindicator.h"

#include <QGraphicsScene>
#include <QTimeLine>

namespace Ui {
 class MainWindow;
}

class MainWindow : public QMainWindow
{
 Q_OBJECT
public:
 enum ScreenOrientation {
 ScreenOrientationLockPortrait,
 ScreenOrientationLockLandscape,
 ScreenOrientationAuto
 };

explicit MainWindow(QWidget '''parent = 0);
 virtual ~MainWindow();

private slots:

 void rotateSpinner(int nValue);

private:

 BusyIndicator''' m_pBusyIndicator;

QGraphicsScene* m_scene;

QTimeLine* m_pTimeLine;

};

#endif // MAINWINDOW_H
  • mainwindow.cpp
#include "mainwindow.h"

#include <QCoreApplication>

#include <QGraphicsView>
#include <QVBoxLayout>

MainWindow::MainWindow(QWidget '''parent)
 : QMainWindow(parent), m_pBusyIndicator(NULL), m_pTimeLine(NULL)
{
 QLayout''' pLayout = new QVBoxLayout();

QGraphicsScene* pScene = new QGraphicsScene(this);
 m_pBusyIndicator = new BusyIndicator();
 pScene->addItem(dynamic_cast<QGraphicsItem*>(m_pBusyIndicator));

QGraphicsView* pView = new QGraphicsView(pScene, this);
 pView->setViewport(this);
 pView->setMinimumHeight(200);
 pView->show();

pLayout->addWidget(pView);
 setLayout(pLayout);

m_pTimeLine = new QTimeLine(1000, this);
 m_pTimeLine->setLoopCount(0);
 m_pTimeLine->setFrameRange(0, 36);

connect(m_pTimeLine, SIGNAL (frameChanged(int)), this, SLOT (rotateSpinner(int)));
 m_pTimeLine->start();

}
//——————————————————————————

MainWindow::~MainWindow()
{
 //Nothing to do
}
//——————————————————————————

void MainWindow::rotateSpinner(int nValue)
{
 qreal nTransX = m_pBusyIndicator->actualOuterRadius();
 m_pBusyIndicator->setTransform(QTransform().translate(nTransX, nTransX).
 rotate(nValue*10).translate(1*nTransX, 1*nTransX));
}
//——————————————————————————