Busy-Indicator-for-QML: Difference between revisions
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
[[Category:Snippets]]<br />[[Category:HowTo]]<br />[[Category:Developing_with_Qt::Qt Quick]]<br />[[Category:Developing_with_Qt::Qt Quick::QML]] | |||
== | [toc align_right="yes&quot; depth="4&quot;] | ||
'''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><br />import QtQuick 2.4<br />import QtQuick.Controls 1.3<br />import QtQuick.Window 2.2 | |||
ApplicationWindow {<br /> title: qsTr("Hello World&quot;)<br /> width: 640<br /> height: 480<br /> visible: true | |||
BusyIndicator {<br /> id: busyIndication<br /> anchors.centerIn: parent<br /> // 'running' defaults to 'true'<br /> } | |||
Button {<br /> anchors.horizontalCenter: parent.horizontalCenter<br /> anchors.bottom: parent.bottom<br /> text: busyIndication.running ? "Stop Busy Indicator&quot; : "Start Busy Indicator&quot;<br /> checkable: true<br /> checked: busyIndication.running<br /> onClicked: busyIndication.running = !busyIndication.running<br /> }<br />}<br /></code> | |||
The implementation of | '''The following describes the implementation of a custom busy indicator for QtQuick 1.''' | ||
This approach minimises the amount of expensive painting calls and key constructions. | 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 ;<s>) | ||
<br />[[Image:http://gallery.theharmers.co.uk/upload/2011/04/30/20110430160839-0a540a36.png|Busy Indicator]] | |||
<br />h2. Implementation | |||
<br />First, here is the class declaration: | |||
<br /><code><br />#ifndef BUSYINDICATOR_H<br />#define BUSYINDICATOR_H | |||
<br />#include <QDeclarativeItem&gt; | |||
<br />class BusyIndicator : public QDeclarativeItem<br />{<br /> Q_OBJECT<br /> Q_PROPERTY( qreal innerRadius READ innerRadius WRITE setInnerRadius NOTIFY innerRadiusChanged )<br /> Q_PROPERTY( qreal outerRadius READ outerRadius WRITE setOuterRadius NOTIFY outerRadiusChanged )<br /> Q_PROPERTY( QColor backgroundColor READ backgroundColor WRITE setBackgroundColor NOTIFY backgroundColorChanged )<br /> Q_PROPERTY( QColor foregroundColor READ foregroundColor WRITE setForegroundColor NOTIFY foregroundColorChanged )<br /> Q_PROPERTY( qreal actualInnerRadius READ actualInnerRadius NOTIFY actualInnerRadiusChanged )<br /> Q_PROPERTY( qreal actualOuterRadius READ actualOuterRadius NOTIFY actualOuterRadiusChanged ) | |||
<br />public:<br /> explicit BusyIndicator( QDeclarativeItem* parent = 0 ); | |||
<br /> void setInnerRadius( const qreal&amp; innerRadius );<br /> qreal innerRadius() const; | |||
<br /> void setOuterRadius( const qreal&amp; outerRadius );<br /> qreal outerRadius() const; | |||
<br /> void setBackgroundColor( const QColor&amp; color );<br /> QColor backgroundColor() const; | |||
<br /> void setForegroundColor( const QColor&amp; color );<br /> QColor foregroundColor() const; | |||
<br /> qreal actualInnerRadius() const;<br /> qreal actualOuterRadius() const; | |||
<br /> virtual void paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0 ); | |||
<br />signals:<br /> void innerRadiusChanged();<br /> void outerRadiusChanged();<br /> void backgroundColorChanged();<br /> void foregroundColorChanged();<br /> void actualInnerRadiusChanged();<br /> void actualOuterRadiusChanged(); | |||
<br />protected slots:<br /> virtual void updateSpinner(); | |||
<br />private:<br /> // User settable properties<br /> qreal m_innerRadius; // In range (0, m_outerRadius]<br /> qreal m_outerRadius; // (m_innerRadius, 1]<br /> QColor m_backgroundColor;<br /> QColor m_foregroundColor; | |||
<br /> // The calculated size, inner and outer radii<br /> qreal m_size;<br /> qreal m_actualInnerRadius;<br /> qreal m_actualOuterRadius; | |||
<br /> QString m_cacheKey;<br />}; | |||
<br />#endif // BUSYINDICATOR_H<br /></code> | |||
<br />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. | |||
<br />Now for the implementation: | |||
<br /><code><br />#include "busyindicator.h&quot; | |||
<br />#include <QConicalGradient&gt;<br />#include <QPainter&gt;<br />#include <QPainterPath&gt;<br />#include <QPixmapCache&gt; | |||
<br />BusyIndicator::BusyIndicator( QDeclarativeItem* parent )<br /> : QDeclarativeItem( parent ),<br /> m_innerRadius( 0.8 ),<br /> m_outerRadius( 1.0 ),<br /> m_backgroundColor( 177, 210, 143, 70 ),<br /> m_foregroundColor( 119, 183, 83, 255 ),<br /> m_actualInnerRadius( 90.0 ),<br /> m_actualOuterRadius( 100.0 ),<br /> m_cacheKey()<br />{<br /> setFlag( QGraphicsItem::ItemHasNoContents, false );<br /> setWidth( 100.0 );<br /> setHeight( 100.0 ); | |||
<br /> updateSpinner(); | |||
<br /> connect( this, SIGNAL( widthChanged() ), SLOT( updateSpinner() ) );<br /> connect( this, SIGNAL( heightChanged() ), SLOT( updateSpinner() ) );<br />} | |||
<br />void BusyIndicator::setInnerRadius( const qreal&amp; innerRadius )<br />{<br /> if ( qFuzzyCompare( m_innerRadius, innerRadius ) )<br /> return;<br /> m_innerRadius = innerRadius;<br /> updateSpinner();<br /> emit innerRadiusChanged();<br />} | |||
<br />qreal BusyIndicator::innerRadius() const<br />{<br /> return m_innerRadius;<br />} | |||
<br />void BusyIndicator::setOuterRadius( const qreal&amp; outerRadius )<br />{<br /> if ( qFuzzyCompare( m_outerRadius, outerRadius ) )<br /> return;<br /> m_outerRadius = outerRadius;<br /> updateSpinner();<br /> emit outerRadiusChanged();<br />} | |||
<br />qreal BusyIndicator::outerRadius() const<br />{<br /> return m_outerRadius;<br />} | |||
<br />void BusyIndicator::setBackgroundColor( const QColor&amp; color )<br />{<br /> if ( m_backgroundColor == color )<br /> return;<br /> m_backgroundColor = color;<br /> updateSpinner();<br /> emit backgroundColorChanged();<br />} | |||
<br />QColor BusyIndicator::backgroundColor() const<br />{<br /> return m_backgroundColor;<br />} | |||
<br />void BusyIndicator::setForegroundColor( const QColor&amp; color )<br />{<br /> if ( m_foregroundColor == color )<br /> return;<br /> m_foregroundColor = color;<br /> updateSpinner();<br /> emit foregroundColorChanged();<br />} | |||
<br />QColor BusyIndicator::foregroundColor() const<br />{<br /> return m_foregroundColor;<br />} | |||
<br />qreal BusyIndicator::actualInnerRadius() const<br />{<br /> return m_actualInnerRadius;<br />} | |||
<br />qreal BusyIndicator::actualOuterRadius() const<br />{<br /> return m_actualOuterRadius;<br />} | |||
<br />void BusyIndicator::updateSpinner()<br />{<br /> // Calculate new inner and outer radii<br /> m_size = qMin( width(), height() );<br /> qreal nCoef = 0.5 * m_size;<br /> m_actualInnerRadius = nCoef * m_innerRadius;<br /> m_actualOuterRadius = nCoef * m_outerRadius; | |||
<br /> // Calculate a new key<br /> m_cacheKey = m_backgroundColor.name();<br /> m_cacheKey ''= "<s>";<br /> m_cacheKey ''= m_foregroundColor.name();<br /> m_cacheKey''= "</s>";<br /> m_cacheKey''= QString::number(m_actualOuterRadius);<br /> m_cacheKey += "</s>";<br /> m_cacheKey ''= QString::number(m_actualInnerRadius); | |||
<br /> emit actualInnerRadiusChanged();<br /> emit actualOuterRadiusChanged();<br />} | |||
<br />void BusyIndicator::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget )<br />{<br /> Q_UNUSED( option );<br /> Q_UNUSED( widget ); | |||
<br /> QPixmap pixmap;<br /> if ( !QPixmapCache::find( m_cacheKey, pixmap ) )<br /> {<br /> // Set up a convenient path<br /> QPainterPath path;<br /> path.setFillRule( Qt::OddEvenFill );<br /> path.addEllipse( QPointF( m_actualOuterRadius, m_actualOuterRadius ), m_actualOuterRadius, m_actualOuterRadius );<br /> path.addEllipse( QPointF( m_actualOuterRadius, m_actualOuterRadius ), m_actualInnerRadius, m_actualInnerRadius ); | |||
<br /> qreal nActualDiameter = 2 * m_actualOuterRadius;<br /> pixmap = QPixmap( nActualDiameter, nActualDiameter );<br /> pixmap.fill( Qt::transparent );<br /> QPainter p( &pixmap ); | |||
<br /> // Draw the ring background<br /> p.setPen( Qt::NoPen );<br /> p.setBrush( m_backgroundColor );<br /> p.setRenderHint( QPainter::Antialiasing );<br /> p.drawPath( path ); | |||
<br /> // Draw the ring foreground<br /> QConicalGradient gradient( QPointF( m_actualOuterRadius, m_actualOuterRadius ), 0.0 );<br /> gradient.setColorAt( 0.0, Qt::transparent );<br /> gradient.setColorAt( 0.05, m_foregroundColor );<br /> gradient.setColorAt( 0.8, Qt::transparent );<br /> p.setBrush( gradient );<br /> p.drawPath( path );<br /> p.end(); | |||
<br /> QPixmapCache::insert( m_cacheKey, pixmap );<br /> } | |||
<br /> // Draw pixmap at center of item<br /> painter->drawPixmap( 0.5 * ( width() - m_size ), 0.5 * ( height() - m_size ), pixmap );<br />}<br /></code> | |||
<br />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: | |||
<br />* Height<br />* Width<br />* Inner radius<br />* Outer radius<br />* Background color<br />* Foreground color | |||
<br />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. | |||
<br />This approach minimises the amount of expensive painting calls and key constructions. | |||
<br />h2. Usage | |||
<br />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: | |||
<br /><code><br />qmlRegisterType&lt;BusyIndicator&gt;( "ZapBsComponents&quot;, 1, 0, "BusyIndicator&quot; );<br /></code> | |||
<br />Then in your QML scene you need to instruct the QML backend to import this collection (of 1) components with: | |||
<br /><code><br />import ZapBsComponents 1.0<br /></code> | |||
<br />You are now ready to roll. | |||
<br />h3. Independent Usage | |||
<br /><code><br />import QtQuick 1.0<br />import ZapBsComponents 1.0 | |||
<br />Rectangle {<br /> id: root<br /> width: 640<br /> height: 360 | |||
<br /> // Trying out the new BusyIndicator custom item<br /> BusyIndicator {<br /> id: busy1<br /> anchors.centerIn: parent | |||
<br /> // Make the ring do something interesting<br /> RotationAnimation<br /> {<br /> target: busy1<br /> property: "rotation&quot; // Suppress a warning<br /> from: 0<br /> to: 360<br /> direction: RotationAnimation.Clockwise<br /> duration: 1000<br /> loops: Animation.Infinite<br /> running: true<br /> }<br /> }<br />}<br /></code> | |||
<br />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. | |||
<br />h3. Compound Usage Within Another Component | |||
<br />It is also easy to include the BusyIndicator into compound components. One example might be for slow to load images: | |||
<br /><code><br />import QtQuick 1.0<br />import ZapBsComponents 1.0 | |||
<br />Item {<br /> id: container<br /> property alias source: image.source<br /> property alias fillMode: image.fillMode | |||
<br /> Image {<br /> id: image<br /> anchors.fill: parent<br /> } | |||
<br /> BusyIndicator {<br /> id: busyIndicator<br /> anchors.fill: parent<br /> visible: image.status != Image.Ready | |||
<br /> RotationAnimation<br /> {<br /> target: busyIndicator<br /> property: "rotation&quot; // Suppress a warning<br /> from: 0<br /> to: 360<br /> direction: RotationAnimation.Clockwise<br /> duration: 1000<br /> loops: Animation.Infinite<br /> running: image.status != Image.Ready<br /> }<br /> }<br />}<br /></code> | |||
<br />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. | |||
<br />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&quot;:http://developer.qt.nokia.com/wiki/QML_Progress_Spinner. | |||
<br />h3. Independent Usage as Widget | |||
<br />This implementation of a busy indicator can also be used without QML. It can be added as widget through "QGraphicsView&quot;:http://developer.qt.nokia.com/doc/qt-4.7/qgraphicsview.html and "QGraphicsScene&quot;:http://developer.qt.nokia.com/doc/qt-4.7/qgraphicsscene.html to a "layout&quot;:http://developer.qt.nokia.com/doc/qt-4.7/qlayout.html and animated with "QTimeLine&quot;:http://developer.qt.nokia.com/doc/qt-4.7/qtimeline.html as shown at the following example. It is important to note that the viewport must be set in order to display the busy indicator. | |||
<br />h4. Example | |||
<br />* pro file | |||
<br /><code>QT''= declarative<code> | |||
* mainwindow.h<br /></code><br />#ifndef MAINWINDOW_H<br />#define MAINWINDOW_H | |||
#include <QtGui/QMainWindow&gt;<br />#include "busyindicator.h&quot; | |||
#include <QGraphicsScene&gt;<br />#include <QTimeLine&gt; | |||
namespace Ui {<br /> class MainWindow;<br />} | |||
class MainWindow : public QMainWindow<br />{<br /> Q_OBJECT<br />public:<br /> enum ScreenOrientation {<br /> ScreenOrientationLockPortrait,<br /> ScreenOrientationLockLandscape,<br /> ScreenOrientationAuto<br /> }; | |||
explicit MainWindow(QWidget '''parent = 0);<br /> virtual ~MainWindow(); | |||
<br />private slots: | |||
<br /> void rotateSpinner(int nValue); | |||
<br />private: | |||
<br /> BusyIndicator''' m_pBusyIndicator; | |||
QGraphicsScene* m_scene; | |||
QTimeLine* m_pTimeLine; | |||
}; | |||
#endif // MAINWINDOW_H | |||
<code> | |||
* mainwindow.cpp<br /></code><br />#include "mainwindow.h&quot; | |||
#include <QtCore/QCoreApplication&gt; | |||
#include <QGraphicsView&gt;<br />#include <QVBoxLayout&gt; | |||
MainWindow::MainWindow(QWidget '''parent)<br /> : QMainWindow(parent), m_pBusyIndicator(NULL), m_pTimeLine(NULL)<br />{<br /> QLayout''' pLayout = new QVBoxLayout(); | |||
* | QGraphicsScene* pScene = new QGraphicsScene(this);<br /> m_pBusyIndicator = new BusyIndicator();<br /> pScene->addItem(dynamic_cast&lt;QGraphicsItem*>(m_pBusyIndicator)); | ||
= | QGraphicsView* pView = new QGraphicsView(pScene, this);<br /> pView->setViewport(this);<br /> pView->setMinimumHeight(200);<br /> pView->show(); | ||
pLayout->addWidget(pView);<br /> setLayout(pLayout); | |||
m_pTimeLine = new QTimeLine(1000, this);<br /> m_pTimeLine->setLoopCount(0);<br /> m_pTimeLine->setFrameRange(0, 36); | |||
connect(m_pTimeLine, SIGNAL (frameChanged(int)), this, SLOT (rotateSpinner(int)));<br /> m_pTimeLine->start(); | |||
}<br />//—————————————————————————— | |||
MainWindow::~MainWindow()<br />{<br /> //Nothing to do<br />}<br />//—————————————————————————— | |||
void MainWindow::rotateSpinner(int nValue)<br />{<br /> qreal nTransX = m_pBusyIndicator->actualOuterRadius();<br /> m_pBusyIndicator->setTransform(QTransform().translate(nTransX, nTransX).<br /> rotate(nValue*10).translate(–1*nTransX, –1*nTransX));<br />}<br />//—————————————————————————— | |||
<code> |
Revision as of 14:35, 23 February 2015
[toc align_right="yes" depth="4"]
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:
<br />import QtQuick 2.4<br />import QtQuick.Controls 1.3<br />import QtQuick.Window 2.2
ApplicationWindow {<br /> title: qsTr("Hello World&quot;)<br /> width: 640<br /> height: 480<br /> visible: true
BusyIndicator {<br /> id: busyIndication<br /> anchors.centerIn: parent<br /> // 'running' defaults to 'true'<br /> }
Button {<br /> anchors.horizontalCenter: parent.horizontalCenter<br /> anchors.bottom: parent.bottom<br /> text: busyIndication.running ? "Stop Busy Indicator&quot; : "Start Busy Indicator&quot;<br /> checkable: true<br /> checked: busyIndication.running<br /> onClicked: busyIndication.running = !busyIndication.running<br /> }<br />}<br />
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 ;)
Busy Indicator
h2. Implementation
First, here is the class declaration:
<br />#ifndef BUSYINDICATOR_H<br />#define BUSYINDICATOR_H
<br />#include <QDeclarativeItem&gt;
<br />class BusyIndicator : public QDeclarativeItem<br />{<br /> Q_OBJECT<br /> Q_PROPERTY( qreal innerRadius READ innerRadius WRITE setInnerRadius NOTIFY innerRadiusChanged )<br /> Q_PROPERTY( qreal outerRadius READ outerRadius WRITE setOuterRadius NOTIFY outerRadiusChanged )<br /> Q_PROPERTY( QColor backgroundColor READ backgroundColor WRITE setBackgroundColor NOTIFY backgroundColorChanged )<br /> Q_PROPERTY( QColor foregroundColor READ foregroundColor WRITE setForegroundColor NOTIFY foregroundColorChanged )<br /> Q_PROPERTY( qreal actualInnerRadius READ actualInnerRadius NOTIFY actualInnerRadiusChanged )<br /> Q_PROPERTY( qreal actualOuterRadius READ actualOuterRadius NOTIFY actualOuterRadiusChanged )
<br />public:<br /> explicit BusyIndicator( QDeclarativeItem* parent = 0 );
<br /> void setInnerRadius( const qreal&amp; innerRadius );<br /> qreal innerRadius() const;
<br /> void setOuterRadius( const qreal&amp; outerRadius );<br /> qreal outerRadius() const;
<br /> void setBackgroundColor( const QColor&amp; color );<br /> QColor backgroundColor() const;
<br /> void setForegroundColor( const QColor&amp; color );<br /> QColor foregroundColor() const;
<br /> qreal actualInnerRadius() const;<br /> qreal actualOuterRadius() const;
<br /> virtual void paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0 );
<br />signals:<br /> void innerRadiusChanged();<br /> void outerRadiusChanged();<br /> void backgroundColorChanged();<br /> void foregroundColorChanged();<br /> void actualInnerRadiusChanged();<br /> void actualOuterRadiusChanged();
<br />protected slots:<br /> virtual void updateSpinner();
<br />private:<br /> // User settable properties<br /> qreal m_innerRadius; // In range (0, m_outerRadius]<br /> qreal m_outerRadius; // (m_innerRadius, 1]<br /> QColor m_backgroundColor;<br /> QColor m_foregroundColor;
<br /> // The calculated size, inner and outer radii<br /> qreal m_size;<br /> qreal m_actualInnerRadius;<br /> qreal m_actualOuterRadius;
<br /> QString m_cacheKey;<br />};
<br />#endif // BUSYINDICATOR_H<br />
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:
<br />#include "busyindicator.h&quot;
<br />#include <QConicalGradient&gt;<br />#include <QPainter&gt;<br />#include <QPainterPath&gt;<br />#include <QPixmapCache&gt;
<br />BusyIndicator::BusyIndicator( QDeclarativeItem* parent )<br /> : QDeclarativeItem( parent ),<br /> m_innerRadius( 0.8 ),<br /> m_outerRadius( 1.0 ),<br /> m_backgroundColor( 177, 210, 143, 70 ),<br /> m_foregroundColor( 119, 183, 83, 255 ),<br /> m_actualInnerRadius( 90.0 ),<br /> m_actualOuterRadius( 100.0 ),<br /> m_cacheKey()<br />{<br /> setFlag( QGraphicsItem::ItemHasNoContents, false );<br /> setWidth( 100.0 );<br /> setHeight( 100.0 );
<br /> updateSpinner();
<br /> connect( this, SIGNAL( widthChanged() ), SLOT( updateSpinner() ) );<br /> connect( this, SIGNAL( heightChanged() ), SLOT( updateSpinner() ) );<br />}
<br />void BusyIndicator::setInnerRadius( const qreal&amp; innerRadius )<br />{<br /> if ( qFuzzyCompare( m_innerRadius, innerRadius ) )<br /> return;<br /> m_innerRadius = innerRadius;<br /> updateSpinner();<br /> emit innerRadiusChanged();<br />}
<br />qreal BusyIndicator::innerRadius() const<br />{<br /> return m_innerRadius;<br />}
<br />void BusyIndicator::setOuterRadius( const qreal&amp; outerRadius )<br />{<br /> if ( qFuzzyCompare( m_outerRadius, outerRadius ) )<br /> return;<br /> m_outerRadius = outerRadius;<br /> updateSpinner();<br /> emit outerRadiusChanged();<br />}
<br />qreal BusyIndicator::outerRadius() const<br />{<br /> return m_outerRadius;<br />}
<br />void BusyIndicator::setBackgroundColor( const QColor&amp; color )<br />{<br /> if ( m_backgroundColor == color )<br /> return;<br /> m_backgroundColor = color;<br /> updateSpinner();<br /> emit backgroundColorChanged();<br />}
<br />QColor BusyIndicator::backgroundColor() const<br />{<br /> return m_backgroundColor;<br />}
<br />void BusyIndicator::setForegroundColor( const QColor&amp; color )<br />{<br /> if ( m_foregroundColor == color )<br /> return;<br /> m_foregroundColor = color;<br /> updateSpinner();<br /> emit foregroundColorChanged();<br />}
<br />QColor BusyIndicator::foregroundColor() const<br />{<br /> return m_foregroundColor;<br />}
<br />qreal BusyIndicator::actualInnerRadius() const<br />{<br /> return m_actualInnerRadius;<br />}
<br />qreal BusyIndicator::actualOuterRadius() const<br />{<br /> return m_actualOuterRadius;<br />}
<br />void BusyIndicator::updateSpinner()<br />{<br /> // Calculate new inner and outer radii<br /> m_size = qMin( width(), height() );<br /> qreal nCoef = 0.5 * m_size;<br /> m_actualInnerRadius = nCoef * m_innerRadius;<br /> m_actualOuterRadius = nCoef * m_outerRadius;
<br /> // Calculate a new key<br /> m_cacheKey = m_backgroundColor.name();<br /> m_cacheKey ''= "<s>";<br /> m_cacheKey ''= m_foregroundColor.name();<br /> m_cacheKey''= "</s>";<br /> m_cacheKey''= QString::number(m_actualOuterRadius);<br /> m_cacheKey += "</s>";<br /> m_cacheKey ''= QString::number(m_actualInnerRadius);
<br /> emit actualInnerRadiusChanged();<br /> emit actualOuterRadiusChanged();<br />}
<br />void BusyIndicator::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget )<br />{<br /> Q_UNUSED( option );<br /> Q_UNUSED( widget );
<br /> QPixmap pixmap;<br /> if ( !QPixmapCache::find( m_cacheKey, pixmap ) )<br /> {<br /> // Set up a convenient path<br /> QPainterPath path;<br /> path.setFillRule( Qt::OddEvenFill );<br /> path.addEllipse( QPointF( m_actualOuterRadius, m_actualOuterRadius ), m_actualOuterRadius, m_actualOuterRadius );<br /> path.addEllipse( QPointF( m_actualOuterRadius, m_actualOuterRadius ), m_actualInnerRadius, m_actualInnerRadius );
<br /> qreal nActualDiameter = 2 * m_actualOuterRadius;<br /> pixmap = QPixmap( nActualDiameter, nActualDiameter );<br /> pixmap.fill( Qt::transparent );<br /> QPainter p( &pixmap );
<br /> // Draw the ring background<br /> p.setPen( Qt::NoPen );<br /> p.setBrush( m_backgroundColor );<br /> p.setRenderHint( QPainter::Antialiasing );<br /> p.drawPath( path );
<br /> // Draw the ring foreground<br /> QConicalGradient gradient( QPointF( m_actualOuterRadius, m_actualOuterRadius ), 0.0 );<br /> gradient.setColorAt( 0.0, Qt::transparent );<br /> gradient.setColorAt( 0.05, m_foregroundColor );<br /> gradient.setColorAt( 0.8, Qt::transparent );<br /> p.setBrush( gradient );<br /> p.drawPath( path );<br /> p.end();
<br /> QPixmapCache::insert( m_cacheKey, pixmap );<br /> }
<br /> // Draw pixmap at center of item<br /> painter->drawPixmap( 0.5 * ( width() - m_size ), 0.5 * ( height() - m_size ), pixmap );<br />}<br />
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.
h2. 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:
<br />qmlRegisterType&lt;BusyIndicator&gt;( "ZapBsComponents&quot;, 1, 0, "BusyIndicator&quot; );<br />
Then in your QML scene you need to instruct the QML backend to import this collection (of 1) components with:
<br />import ZapBsComponents 1.0<br />
You are now ready to roll.
h3. Independent Usage
<br />import QtQuick 1.0<br />import ZapBsComponents 1.0
<br />Rectangle {<br /> id: root<br /> width: 640<br /> height: 360
<br /> // Trying out the new BusyIndicator custom item<br /> BusyIndicator {<br /> id: busy1<br /> anchors.centerIn: parent
<br /> // Make the ring do something interesting<br /> RotationAnimation<br /> {<br /> target: busy1<br /> property: "rotation&quot; // Suppress a warning<br /> from: 0<br /> to: 360<br /> direction: RotationAnimation.Clockwise<br /> duration: 1000<br /> loops: Animation.Infinite<br /> running: true<br /> }<br /> }<br />}<br />
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.
h3. 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:
<br />import QtQuick 1.0<br />import ZapBsComponents 1.0
<br />Item {<br /> id: container<br /> property alias source: image.source<br /> property alias fillMode: image.fillMode
<br /> Image {<br /> id: image<br /> anchors.fill: parent<br /> }
<br /> BusyIndicator {<br /> id: busyIndicator<br /> anchors.fill: parent<br /> visible: image.status != Image.Ready
<br /> RotationAnimation<br /> {<br /> target: busyIndicator<br /> property: "rotation&quot; // Suppress a warning<br /> from: 0<br /> to: 360<br /> direction: RotationAnimation.Clockwise<br /> duration: 1000<br /> loops: Animation.Infinite<br /> running: image.status != Image.Ready<br /> }<br /> }<br />}<br />
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":http://developer.qt.nokia.com/wiki/QML_Progress_Spinner.
h3. Independent Usage as Widget
This implementation of a busy indicator can also be used without QML. It can be added as widget through "QGraphicsView":http://developer.qt.nokia.com/doc/qt-4.7/qgraphicsview.html and "QGraphicsScene":http://developer.qt.nokia.com/doc/qt-4.7/qgraphicsscene.html to a "layout":http://developer.qt.nokia.com/doc/qt-4.7/qlayout.html and animated with "QTimeLine":http://developer.qt.nokia.com/doc/qt-4.7/qtimeline.html as shown at the following example. It is important to note that the viewport must be set in order to display the busy indicator.
h4. Example
* pro file
QT''= declarative<code>
* mainwindow.h<br />
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
- include <QtGui/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<br />
#include "mainwindow.h"
- include <QtCore/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));
}
//——————————————————————————