Busy-Indicator-for-QML: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
(redirect)
 
(6 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:Snippets]]<br />[[Category:HowTo]]<br />[[Category:Developing_with_Qt::Qt Quick]]<br />[[Category:Developing_with_Qt::Qt Quick::QML]]
#REDIRECT [[Busy Indicator for QML]]
 
[toc align_right=&quot;yes&amp;quot; depth=&quot;4&amp;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(&quot;Hello World&amp;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 ? &quot;Stop Busy Indicator&amp;quot; : &quot;Start Busy Indicator&amp;quot;<br /> checkable: true<br /> checked: busyIndication.running<br /> onClicked: busyIndication.running = !busyIndication.running<br /> }<br />}<br /></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 ;<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 &lt;QDeclarativeItem&amp;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;amp; innerRadius );<br /> qreal innerRadius() const;
<br /> void setOuterRadius( const qreal&amp;amp; outerRadius );<br /> qreal outerRadius() const;
<br /> void setBackgroundColor( const QColor&amp;amp; color );<br /> QColor backgroundColor() const;
<br /> void setForegroundColor( const QColor&amp;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 &quot;busyindicator.h&amp;quot;
<br />#include &lt;QConicalGradient&amp;gt;<br />#include &lt;QPainter&amp;gt;<br />#include &lt;QPainterPath&amp;gt;<br />#include &lt;QPixmapCache&amp;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;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;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;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;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 ''= &quot;<s>&quot;;<br /> m_cacheKey ''= m_foregroundColor.name();<br /> m_cacheKey''= &quot;</s>&quot;;<br /> m_cacheKey''= QString::number(m_actualOuterRadius);<br /> m_cacheKey += &quot;</s>&quot;;<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( &amp;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-&gt;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&amp;lt;BusyIndicator&amp;gt;( &quot;ZapBsComponents&amp;quot;, 1, 0, &quot;BusyIndicator&amp;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: &quot;rotation&amp;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: &quot;rotation&amp;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 &quot;snippet&amp;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 &quot;QGraphicsView&amp;quot;:http://developer.qt.nokia.com/doc/qt-4.7/qgraphicsview.html and &quot;QGraphicsScene&amp;quot;:http://developer.qt.nokia.com/doc/qt-4.7/qgraphicsscene.html to a &quot;layout&amp;quot;:http://developer.qt.nokia.com/doc/qt-4.7/qlayout.html and animated with &quot;QTimeLine&amp;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 &lt;QtGui/QMainWindow&amp;gt;<br />#include &quot;busyindicator.h&amp;quot;
 
#include &lt;QGraphicsScene&amp;gt;<br />#include &lt;QTimeLine&amp;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 &quot;mainwindow.h&amp;quot;
 
#include &lt;QtCore/QCoreApplication&amp;gt;
 
#include &lt;QGraphicsView&amp;gt;<br />#include &lt;QVBoxLayout&amp;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-&gt;addItem(dynamic_cast&amp;lt;QGraphicsItem*&gt;(m_pBusyIndicator));
 
QGraphicsView* pView = new QGraphicsView(pScene, this);<br /> pView-&gt;setViewport(this);<br /> pView-&gt;setMinimumHeight(200);<br /> pView-&gt;show();
 
pLayout-&gt;addWidget(pView);<br /> setLayout(pLayout);
 
m_pTimeLine = new QTimeLine(1000, this);<br /> m_pTimeLine-&gt;setLoopCount(0);<br /> m_pTimeLine-&gt;setFrameRange(0, 36);
 
connect(m_pTimeLine, SIGNAL (frameChanged(int)), this, SLOT (rotateSpinner(int)));<br /> m_pTimeLine-&gt;start();
 
}<br />//——————————————————————————
 
MainWindow::~MainWindow()<br />{<br /> //Nothing to do<br />}<br />//——————————————————————————
 
void MainWindow::rotateSpinner(int nValue)<br />{<br /> qreal nTransX = m_pBusyIndicator-&gt;actualOuterRadius();<br /> m_pBusyIndicator-&gt;setTransform(QTransform().translate(nTransX, nTransX).<br /> rotate(nValue*10).translate(–1*nTransX, –1*nTransX));<br />}<br />//——————————————————————————
 
<code>

Latest revision as of 10:32, 28 June 2015