<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-x11-free-3.3.8/doc/tutorial2.doc:729 --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Canvas Control</title> <style type="text/css"><!-- fn { margin-left: 1cm; text-indent: -1cm; } a:link { color: #004faf; text-decoration: none } a:visited { color: #672967; text-decoration: none } body { background: #ffffff; color: black; } --></style> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr bgcolor="#E5E5E5"> <td valign=center> <a href="index.html"> <font color="#004faf">Home</font></a> | <a href="classes.html"> <font color="#004faf">All Classes</font></a> | <a href="mainclasses.html"> <font color="#004faf">Main Classes</font></a> | <a href="annotated.html"> <font color="#004faf">Annotated</font></a> | <a href="groups.html"> <font color="#004faf">Grouped Classes</font></a> | <a href="functions.html"> <font color="#004faf">Functions</font></a> </td> <td align="right" valign="center"><img src="logo32.png" align="right" width="64" height="32" border="0"></td></tr></table><h1 align=center>Canvas Control</h1> <p> <p> We draw pie segments (or bar chart bars), and any labels, on a canvas. The canvas is presented to the user through a canvas view. The drawElements() function is called to redraw the canvas when necessary. <p> (Extracts from <tt>chartform_canvas.cpp</tt>.) <p> <h2> drawElements() </h2> <a name="1"></a><p> <pre> void ChartForm::drawElements() { <a href="qcanvasitemlist.html">QCanvasItemList</a> list = m_canvas->allItems(); for ( QCanvasItemList::iterator it = list.<a href="qvaluelist.html#begin">begin</a>(); it != list.<a href="qvaluelist.html#end">end</a>(); ++it ) delete *it; </pre> <p> The first thing we do in drawElements() is delete all the existing canvas items. <p> <pre> // 360 * 16 for pies; Qt works with 16ths of degrees int scaleFactor = m_chartType == PIE ? 5760 : m_chartType == VERTICAL_BAR ? m_canvas->height() : m_canvas->width(); </pre> <p> Next we calculate the scale factor which depends on the type of chart we're going to draw. <p> <pre> double biggest = 0.0; int count = 0; double total = 0.0; static double scales[MAX_ELEMENTS]; for ( int i = 0; i < MAX_ELEMENTS; ++i ) { if ( m_elements[i].isValid() ) { double value = m_elements[i].value(); count++; total += value; if ( value > biggest ) biggest = value; scales[i] = m_elements[i].value() * scaleFactor; } } if ( count ) { // 2nd loop because of total and biggest for ( int i = 0; i < MAX_ELEMENTS; ++i ) if ( m_elements[i].isValid() ) if ( m_chartType == PIE ) scales[i] = (m_elements[i].value() * scaleFactor) / total; else scales[i] = (m_elements[i].value() * scaleFactor) / biggest; </pre> <p> We will need to know how many values there are, the biggest value and the total value so that we can create pie segments or bars that are correctly scaled. We store the scaled values in the <tt>scales</tt> array. <p> <pre> switch ( m_chartType ) { case PIE: drawPieChart( scales, total, count ); break; case VERTICAL_BAR: drawVerticalBarChart( scales, total, count ); break; case HORIZONTAL_BAR: drawHorizontalBarChart( scales, total, count ); break; } } </pre> <p> Now that we have the necessary information we call the relevant drawing function, passing in the scaled values, the total and the count. <p> <pre> m_canvas->update(); </pre> <p> Finally we update() the canvas to make the changes visible. <p> <h3> drawHorizontalBarChart() </h3> <a name="1-1"></a><p> We'll review just one of the drawing functions, to see how canvas items are created and placed on a canvas since this tutorial is about Qt rather than good (or bad) algorithms for drawing charts. <p> <pre> void ChartForm::drawHorizontalBarChart( const double scales[], double total, int count ) { </pre> <p> To draw a horizontal bar chart we need the array of scaled values, the total value (so that we can calculate and draw percentages if required) and a count of the number of values. <p> <pre> double width = m_canvas->width(); double height = m_canvas->height(); int proheight = int(height / count); int y = 0; </pre> <p> We retrieve the width and height of the canvas and calculate the proportional height (<tt>proheight</tt>). We set the initial <tt>y</tt> position to 0. <p> <pre> <a href="qpen.html">QPen</a> pen; <a name="x2575"></a> pen.<a href="qpen.html#setStyle">setStyle</a>( NoPen ); </pre> <p> We create a pen that we will use to draw each bar (rectangle); we set it to <tt>NoPen</tt> so that no outlines are drawn. <p> <pre> for ( int i = 0; i < MAX_ELEMENTS; ++i ) { if ( m_elements[i].isValid() ) { int extent = int(scales[i]); </pre> <p> We iterate over every element in the element vector, skipping invalid elements. The extent of each bar (its length) is simply its scaled value. <p> <pre> <a href="qcanvasrectangle.html">QCanvasRectangle</a> *rect = new <a href="qcanvasrectangle.html">QCanvasRectangle</a>( 0, y, extent, proheight, m_canvas ); <a name="x2572"></a> rect-><a href="qcanvaspolygonalitem.html#setBrush">setBrush</a>( QBrush( m_elements[i].valueColor(), BrushStyle(m_elements[i].valuePattern()) ) ); <a name="x2573"></a> rect-><a href="qcanvaspolygonalitem.html#setPen">setPen</a>( pen ); <a name="x2570"></a> rect-><a href="qcanvasitem.html#setZ">setZ</a>( 0 ); <a name="x2571"></a> rect-><a href="qcanvasitem.html#show">show</a>(); </pre> <p> We create a new <a href="qcanvasrectangle.html">QCanvasRectangle</a> for each bar with an x position of 0 (since this is a horizontal bar chart every bar begins at the left), a y value that starts at 0 and grows by the height of each bar as each one is drawn, the height of the bar and the canvas that the bar should be drawn on. We then set the bar's brush to the color and pattern that the user has specified for the element, set the pen to the pen we created earlier (i.e. to <tt>NoPen</tt>) and we place the bar at position 0 in the Z-order. Finally we call show() to draw the bar on the canvas. <p> <pre> <a href="qstring.html">QString</a> label = m_elements[i].label(); <a name="x2576"></a> if ( !label.<a href="qstring.html#isEmpty">isEmpty</a>() || m_addValues != NO ) { double proX = m_elements[i].proX( HORIZONTAL_BAR ); double proY = m_elements[i].proY( HORIZONTAL_BAR ); if ( proX < 0 || proY < 0 ) { proX = 0; proY = y / height; } </pre> <p> If the user has specified a label for the element or asked for the values (or percentages) to be shown, we also draw a canvas text item. We created our own CanvasText class (see later) because we want to store the corresponding element index (in the element vector) in each canvas text item. We extract the proportional x and y values from the element. If either is < 0 then they have not been positioned by the user so we must calculate positions for them. We set the label's x value to 0 (left) and the y value to the top of the bar (so that the label's top-left will be at this x, y position). <p> <pre> label = valueLabel( label, m_elements[i].value(), total ); </pre> <p> We then call a helper function valueLabel() which returns a string containing the label text. (The valueLabel() function adds on the value or percentage to the textual label if the user has set the appropriate options.) <p> <pre> CanvasText *text = new CanvasText( i, label, m_font, m_canvas ); <a name="x2574"></a> text-><a href="qcanvastext.html#setColor">setColor</a>( m_elements[i].labelColor() ); <a name="x2568"></a> text-><a href="qcanvasitem.html#setX">setX</a>( proX * width ); <a name="x2569"></a> text-><a href="qcanvasitem.html#setY">setY</a>( proY * height ); text-><a href="qcanvasitem.html#setZ">setZ</a>( 1 ); text-><a href="qcanvasitem.html#show">show</a>(); m_elements[i].setProX( HORIZONTAL_BAR, proX ); m_elements[i].setProY( HORIZONTAL_BAR, proY ); </pre> <p> We then create a CanvasText item, passing it the index of this element in the element vector, and the label, font and canvas to use. We set the text item's text color to the color specified by the user and set the item's x and y positions proportional to the canvas's width and height. We set the Z-order to 1 so that the text item will always be above (in front of) the bar (whose Z-order is 0). We call show() to draw the text item on the canvas, and set the element's relative x and y positions. <p> <pre> } y += proheight; </pre> <p> After drawing a bar and possibly its label, we increment y by the proportional height ready to draw the next element. <p> <pre> } } } </pre> <p> <h2> Subclassing <a href="qcanvastext.html">QCanvasText</a> </h2> <a name="2"></a><p> (Extracts from <tt>canvastext.h</tt>.) <p> <pre> class CanvasText : public <a href="qcanvastext.html">QCanvasText</a> { public: enum { CANVAS_TEXT = 1100 }; CanvasText( int index, QCanvas *canvas ) : <a href="qcanvastext.html">QCanvasText</a>( canvas ), m_index( index ) {} CanvasText( int index, const <a href="qstring.html">QString</a>& text, QCanvas *canvas ) : <a href="qcanvastext.html">QCanvasText</a>( text, canvas ), m_index( index ) {} CanvasText( int index, const <a href="qstring.html">QString</a>& text, QFont font, QCanvas *canvas ) : <a href="qcanvastext.html">QCanvasText</a>( text, font, canvas ), m_index( index ) {} int index() const { return m_index; } void setIndex( int index ) { m_index = index; } int rtti() const { return CANVAS_TEXT; } private: int m_index; }; </pre> <p> Our CanvasText subclass is a very simple specialisation of <a href="qcanvastext.html">QCanvasText</a>. All we've done is added a single private member <tt>m_index</tt> which holds the element vector index of the element associated with this text item, and provided a getter and setter for this value. <p> <h2> Subclassing <a href="qcanvasview.html">QCanvasView</a> </h2> <a name="3"></a><p> (Extracts from <tt>canvasview.h</tt>.) <p> <pre> class CanvasView : public <a href="qcanvasview.html">QCanvasView</a> { <a href="metaobjects.html#Q_OBJECT">Q_OBJECT</a> public: CanvasView( <a href="qcanvas.html">QCanvas</a> *canvas, ElementVector *elements, <a href="qwidget.html">QWidget</a>* parent = 0, const char* name = "canvas view", WFlags f = 0 ) : <a href="qcanvasview.html">QCanvasView</a>( canvas, parent, name, f ), m_movingItem(0), m_elements( elements ) {} protected: void viewportResizeEvent( <a href="qresizeevent.html">QResizeEvent</a> *e ); void contentsMousePressEvent( <a href="qmouseevent.html">QMouseEvent</a> *e ); void contentsMouseMoveEvent( <a href="qmouseevent.html">QMouseEvent</a> *e ); void contentsContextMenuEvent( <a href="qcontextmenuevent.html">QContextMenuEvent</a> *e ); private: <a href="qcanvasitem.html">QCanvasItem</a> *m_movingItem; <a href="qpoint.html">QPoint</a> m_pos; ElementVector *m_elements; }; </pre> <p> We need to subclass <a href="qcanvasview.html">QCanvasView</a> so that we can handle: <ol type=1> <li> Context menu requests. <li> Form resizing. <li> Users dragging labels to arbitrary positions. </ol> <p> To support these we store a pointer to the canvas item that is being moved and its last position. We also store a pointer to the element vector. <p> <h3> Supporting Context Menus </h3> <a name="3-1"></a><p> (Extracts from <tt>canvasview.cpp</tt>.) <p> <pre> <a name="x2584"></a>void CanvasView::<a href="qscrollview.html#contentsContextMenuEvent">contentsContextMenuEvent</a>( <a href="qcontextmenuevent.html">QContextMenuEvent</a> * ) { <a name="x2579"></a> ((ChartForm*)<a href="qobject.html#parent">parent</a>())->optionsMenu->exec( QCursor::<a href="qcursor.html#pos">pos</a>() ); } </pre> <p> When the user invokes a context menu (e.g. by right-clicking on most platforms) we cast the canvas view's parent (which is the chart form) to the right type and then exec()ute the options menu at the cursor position. <p> <h3> Handling Resizing </h3> <a name="3-2"></a><p> <pre> <a name="x2587"></a>void CanvasView::<a href="qscrollview.html#viewportResizeEvent">viewportResizeEvent</a>( <a href="qresizeevent.html">QResizeEvent</a> *e ) { <a name="x2583"></a> <a href="qcanvasview.html#canvas">canvas</a>()->resize( e-><a href="qresizeevent.html#size">size</a>().width(), e-><a href="qresizeevent.html#size">size</a>().height() ); ((ChartForm*)<a href="qobject.html#parent">parent</a>())->drawElements(); } </pre> <p> To resize we simply resize the canvas that the canvas view is presenting to the width and height of the form's client area, then call drawElements() to redraw the chart. Because drawElements() draws everything relative to the canvas's width and height the chart is drawn correctly. <p> <h3> Dragging Labels into Position </h3> <a name="3-3"></a><p> When the user wants to drag a label into position they click it, then drag and release at the new position. <p> <pre> <a name="x2586"></a>void CanvasView::<a href="qscrollview.html#contentsMousePressEvent">contentsMousePressEvent</a>( <a href="qmouseevent.html">QMouseEvent</a> *e ) { <a name="x2580"></a> <a href="qcanvasitemlist.html">QCanvasItemList</a> list = <a href="qcanvasview.html#canvas">canvas</a>()->collisions( e-><a href="qmouseevent.html#pos">pos</a>() ); <a name="x2589"></a><a name="x2588"></a> for ( QCanvasItemList::iterator it = list.<a href="qvaluelist.html#begin">begin</a>(); it != list.<a href="qvaluelist.html#end">end</a>(); ++it ) if ( (*it)->rtti() == CanvasText::CANVAS_TEXT ) { m_movingItem = *it; m_pos = e-><a href="qmouseevent.html#pos">pos</a>(); return; } m_movingItem = 0; } </pre> <p> When the user clicks the mouse we create a list of canvas items that the mouse click "collided" with (if any). We then iterate over this list and if we find a <tt>CanvasText</tt> item we set it as the moving item and record its position. Otherwise we set there to be no moving item. <p> <pre> <a name="x2585"></a>void CanvasView::<a href="qscrollview.html#contentsMouseMoveEvent">contentsMouseMoveEvent</a>( <a href="qmouseevent.html">QMouseEvent</a> *e ) { if ( m_movingItem ) { <a href="qpoint.html">QPoint</a> offset = e-><a href="qmouseevent.html#pos">pos</a>() - m_pos; <a name="x2582"></a><a name="x2581"></a> m_movingItem->moveBy( offset.<a href="qpoint.html#x">x</a>(), offset.<a href="qpoint.html#y">y</a>() ); m_pos = e-><a href="qmouseevent.html#pos">pos</a>(); ChartForm *form = (ChartForm*)<a href="qobject.html#parent">parent</a>(); form->setChanged( TRUE ); int chartType = form->chartType(); CanvasText *item = (CanvasText*)m_movingItem; int i = item->index(); (*m_elements)[i].setProX( chartType, item->x() / canvas()->width() ); (*m_elements)[i].setProY( chartType, item->y() / canvas()->height() ); <a href="qcanvasview.html#canvas">canvas</a>()->update(); } } </pre> <p> As the user drags the mouse, move events are generated. If there is a moving item we calculate the offset from the last mouse position and move the item by this offset amount. We record the new position as the last position. Because the chart has now changed we call setChanged() so that the user will be prompted to save if they attempt to exit or to load an existing chart or to create a new chart. We also update the element's proportional x and y positions for the current chart type to the current x and y positions proportional to the width and height respectively. We know which element to update because when we create each canvas text item we pass it the index position of the element it corresponds to. We subclassed <a href="qcanvastext.html">QCanvasText</a> so that we could set and get this index value. Finally we call update() to make the canvas redraw. <p> <center><table cellpadding="4" cellspacing="2" border="0"> <tr bgcolor="#f0f0f0"> <td valign="top">A <a href="qcanvas.html">QCanvas</a> has no visual representation. To see the contents of a canvas you must create a <a href="qcanvasview.html">QCanvasView</a> to present the canvas. Items only appear in the canvas view if they have been show()n, and then, only if <a href="qcanvas.html#update">QCanvas::update</a>() has been called. By default a QCanvas's background color is white, and by default shapes drawn on the canvas, e.g. <a href="qcanvasrectangle.html">QCanvasRectangle</a>, <a href="qcanvasellipse.html">QCanvasEllipse</a>, etc., have their fill color set to white, so setting a non-white brush color is highly recommended! </table></center> <p> <p align="right"> <a href="tutorial2-05.html">« Presenting the GUI</a> | <a href="tutorial2.html">Contents</a> | <a href="tutorial2-07.html">File Handling »</a> </p> <p> <!-- eof --> <p><address><hr><div align=center> <table width=100% cellspacing=0 border=0><tr> <td>Copyright © 2007 <a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a> <td align=right><div align=right>Qt 3.3.8</div> </table></div></address></body> </html>