source: trunk/doc/html/tutorial2-06.html@ 203

Last change on this file since 203 was 190, checked in by rudi, 14 years ago

reference documentation added

File size: 18.7 KB
Line 
1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-x11-free-3.3.8/doc/tutorial2.doc:729 -->
3<html>
4<head>
5<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6<title>Canvas Control</title>
7<style type="text/css"><!--
8fn { margin-left: 1cm; text-indent: -1cm; }
9a:link { color: #004faf; text-decoration: none }
10a:visited { color: #672967; text-decoration: none }
11body { background: #ffffff; color: black; }
12--></style>
13</head>
14<body>
15
16<table border="0" cellpadding="0" cellspacing="0" width="100%">
17<tr bgcolor="#E5E5E5">
18<td valign=center>
19 <a href="index.html">
20<font color="#004faf">Home</font></a>
21 | <a href="classes.html">
22<font color="#004faf">All&nbsp;Classes</font></a>
23 | <a href="mainclasses.html">
24<font color="#004faf">Main&nbsp;Classes</font></a>
25 | <a href="annotated.html">
26<font color="#004faf">Annotated</font></a>
27 | <a href="groups.html">
28<font color="#004faf">Grouped&nbsp;Classes</font></a>
29 | <a href="functions.html">
30<font color="#004faf">Functions</font></a>
31</td>
32<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>
33
34
35<p>
36<p> We draw pie segments (or bar chart bars), and any labels, on a canvas.
37The canvas is presented to the user through a canvas view. The
38drawElements() function is called to redraw the canvas when necessary.
39<p> (Extracts from <tt>chartform_canvas.cpp</tt>.)
40<p> <h2> drawElements()
41</h2>
42<a name="1"></a><p>
43
44<pre> void ChartForm::drawElements()
45 {
46 <a href="qcanvasitemlist.html">QCanvasItemList</a> list = m_canvas-&gt;allItems();
47 for ( QCanvasItemList::iterator it = list.<a href="qvaluelist.html#begin">begin</a>(); it != list.<a href="qvaluelist.html#end">end</a>(); ++it )
48 delete *it;
49</pre>
50<p> The first thing we do in drawElements() is delete all the existing
51canvas items.
52<p> <pre> // 360 * 16 for pies; Qt works with 16ths of degrees
53 int scaleFactor = m_chartType == PIE ? 5760 :
54 m_chartType == VERTICAL_BAR ? m_canvas-&gt;height() :
55 m_canvas-&gt;width();
56</pre>
57<p> Next we calculate the scale factor which depends on the type of chart
58we're going to draw.
59<p> <pre> double biggest = 0.0;
60 int count = 0;
61 double total = 0.0;
62 static double scales[MAX_ELEMENTS];
63
64 for ( int i = 0; i &lt; MAX_ELEMENTS; ++i ) {
65 if ( m_elements[i].isValid() ) {
66 double value = m_elements[i].value();
67 count++;
68 total += value;
69 if ( value &gt; biggest )
70 biggest = value;
71 scales[i] = m_elements[i].value() * scaleFactor;
72 }
73 }
74
75 if ( count ) {
76 // 2nd loop because of total and biggest
77 for ( int i = 0; i &lt; MAX_ELEMENTS; ++i )
78 if ( m_elements[i].isValid() )
79 if ( m_chartType == PIE )
80 scales[i] = (m_elements[i].value() * scaleFactor) / total;
81 else
82 scales[i] = (m_elements[i].value() * scaleFactor) / biggest;
83</pre>
84<p> We will need to know how many values there are, the biggest value and
85the total value so that we can create pie segments or bars that are
86correctly scaled. We store the scaled values in the <tt>scales</tt> array.
87<p> <pre> switch ( m_chartType ) {
88 case PIE:
89 drawPieChart( scales, total, count );
90 break;
91 case VERTICAL_BAR:
92 drawVerticalBarChart( scales, total, count );
93 break;
94 case HORIZONTAL_BAR:
95 drawHorizontalBarChart( scales, total, count );
96 break;
97 }
98 }
99</pre>
100<p> Now that we have the necessary information we call the relevant
101drawing function, passing in the scaled values, the total and the
102count.
103<p> <pre> m_canvas-&gt;update();
104</pre>
105<p> Finally we update() the canvas to make the changes visible.
106<p> <h3> drawHorizontalBarChart()
107</h3>
108<a name="1-1"></a><p> We'll review just one of the drawing functions, to see how canvas
109items are created and placed on a canvas since this tutorial is about
110Qt rather than good (or bad) algorithms for drawing charts.
111<p> <pre> void ChartForm::drawHorizontalBarChart(
112 const double scales[], double total, int count )
113 {
114</pre>
115<p> To draw a horizontal bar chart we need the array of scaled values, the
116total value (so that we can calculate and draw percentages if
117required) and a count of the number of values.
118<p> <pre> double width = m_canvas-&gt;width();
119 double height = m_canvas-&gt;height();
120 int proheight = int(height / count);
121 int y = 0;
122</pre>
123<p> We retrieve the width and height of the canvas and calculate the
124proportional height (<tt>proheight</tt>). We set the initial <tt>y</tt> position
125to 0.
126<p> <pre> <a href="qpen.html">QPen</a> pen;
127 <a name="x2575"></a> pen.<a href="qpen.html#setStyle">setStyle</a>( NoPen );
128</pre>
129<p> We create a pen that we will use to draw each bar (rectangle); we set
130it to <tt>NoPen</tt> so that no outlines are drawn.
131<p> <pre> for ( int i = 0; i &lt; MAX_ELEMENTS; ++i ) {
132 if ( m_elements[i].isValid() ) {
133 int extent = int(scales[i]);
134</pre>
135<p> We iterate over every element in the element vector, skipping invalid
136elements. The extent of each bar (its length) is simply its scaled
137value.
138<p> <pre> <a href="qcanvasrectangle.html">QCanvasRectangle</a> *rect = new <a href="qcanvasrectangle.html">QCanvasRectangle</a>(
139 0, y, extent, proheight, m_canvas );
140 <a name="x2572"></a> rect-&gt;<a href="qcanvaspolygonalitem.html#setBrush">setBrush</a>( QBrush( m_elements[i].valueColor(),
141 BrushStyle(m_elements[i].valuePattern()) ) );
142 <a name="x2573"></a> rect-&gt;<a href="qcanvaspolygonalitem.html#setPen">setPen</a>( pen );
143 <a name="x2570"></a> rect-&gt;<a href="qcanvasitem.html#setZ">setZ</a>( 0 );
144 <a name="x2571"></a> rect-&gt;<a href="qcanvasitem.html#show">show</a>();
145</pre>
146<p> We create a new <a href="qcanvasrectangle.html">QCanvasRectangle</a> for each bar with an x position of 0
147(since this is a horizontal bar chart every bar begins at the left), a
148y value that starts at 0 and grows by the height of each bar as each
149one is drawn, the height of the bar and the canvas that the bar should
150be drawn on. We then set the bar's brush to the color and pattern that
151the user has specified for the element, set the pen to the pen we
152created earlier (i.e. to <tt>NoPen</tt>) and we place the bar at position 0
153in the Z-order. Finally we call show() to draw the bar on the canvas.
154<p> <pre> <a href="qstring.html">QString</a> label = m_elements[i].label();
155 <a name="x2576"></a> if ( !label.<a href="qstring.html#isEmpty">isEmpty</a>() || m_addValues != NO ) {
156 double proX = m_elements[i].proX( HORIZONTAL_BAR );
157 double proY = m_elements[i].proY( HORIZONTAL_BAR );
158 if ( proX &lt; 0 || proY &lt; 0 ) {
159 proX = 0;
160 proY = y / height;
161 }
162</pre>
163<p> If the user has specified a label for the element or asked for the
164values (or percentages) to be shown, we also draw a canvas text item.
165We created our own CanvasText class (see later) because we want to
166store the corresponding element index (in the element vector) in each
167canvas text item. We extract the proportional x and y values from the
168element. If either is &lt; 0 then they have not been positioned by the
169user so we must calculate positions for them. We set the label's x
170value to 0 (left) and the y value to the top of the bar (so that the
171label's top-left will be at this x, y position).
172<p> <pre> label = valueLabel( label, m_elements[i].value(), total );
173</pre>
174<p> We then call a helper function valueLabel() which returns a string
175containing the label text. (The valueLabel() function adds on the
176value or percentage to the textual label if the user has set the
177appropriate options.)
178<p> <pre> CanvasText *text = new CanvasText( i, label, m_font, m_canvas );
179 <a name="x2574"></a> text-&gt;<a href="qcanvastext.html#setColor">setColor</a>( m_elements[i].labelColor() );
180 <a name="x2568"></a> text-&gt;<a href="qcanvasitem.html#setX">setX</a>( proX * width );
181 <a name="x2569"></a> text-&gt;<a href="qcanvasitem.html#setY">setY</a>( proY * height );
182 text-&gt;<a href="qcanvasitem.html#setZ">setZ</a>( 1 );
183 text-&gt;<a href="qcanvasitem.html#show">show</a>();
184 m_elements[i].setProX( HORIZONTAL_BAR, proX );
185 m_elements[i].setProY( HORIZONTAL_BAR, proY );
186</pre>
187<p> We then create a CanvasText item, passing it the index of this element
188in the element vector, and the label, font and canvas to use. We set
189the text item's text color to the color specified by the user and set
190the item's x and y positions proportional to the canvas's width and
191height. We set the Z-order to 1 so that the text item will always be
192above (in front of) the bar (whose Z-order is 0). We call show() to
193draw the text item on the canvas, and set the element's relative x and
194y positions.
195<p> <pre> }
196 y += proheight;
197</pre>
198<p> After drawing a bar and possibly its label, we increment y by the
199proportional height ready to draw the next element.
200<p> <pre> }
201 }
202 }
203</pre>
204<p> <h2> Subclassing <a href="qcanvastext.html">QCanvasText</a>
205</h2>
206<a name="2"></a><p> (Extracts from <tt>canvastext.h</tt>.)
207<p>
208
209<pre> class CanvasText : public <a href="qcanvastext.html">QCanvasText</a>
210 {
211 public:
212 enum { CANVAS_TEXT = 1100 };
213
214 CanvasText( int index, QCanvas *canvas )
215 : <a href="qcanvastext.html">QCanvasText</a>( canvas ), m_index( index ) {}
216 CanvasText( int index, const <a href="qstring.html">QString</a>&amp; text, QCanvas *canvas )
217 : <a href="qcanvastext.html">QCanvasText</a>( text, canvas ), m_index( index ) {}
218 CanvasText( int index, const <a href="qstring.html">QString</a>&amp; text, QFont font, QCanvas *canvas )
219 : <a href="qcanvastext.html">QCanvasText</a>( text, font, canvas ), m_index( index ) {}
220
221 int index() const { return m_index; }
222 void setIndex( int index ) { m_index = index; }
223
224 int rtti() const { return CANVAS_TEXT; }
225
226 private:
227 int m_index;
228 };
229</pre>
230<p> Our CanvasText subclass is a very simple specialisation of
231<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
232with this text item, and provided a getter and setter for this value.
233<p> <h2> Subclassing <a href="qcanvasview.html">QCanvasView</a>
234</h2>
235<a name="3"></a><p> (Extracts from <tt>canvasview.h</tt>.)
236<p>
237
238<pre> class CanvasView : public <a href="qcanvasview.html">QCanvasView</a>
239 {
240 <a href="metaobjects.html#Q_OBJECT">Q_OBJECT</a>
241 public:
242 CanvasView( <a href="qcanvas.html">QCanvas</a> *canvas, ElementVector *elements,
243 <a href="qwidget.html">QWidget</a>* parent = 0, const char* name = "canvas view",
244 WFlags f = 0 )
245 : <a href="qcanvasview.html">QCanvasView</a>( canvas, parent, name, f ), m_movingItem(0),
246 m_elements( elements ) {}
247
248 protected:
249 void viewportResizeEvent( <a href="qresizeevent.html">QResizeEvent</a> *e );
250 void contentsMousePressEvent( <a href="qmouseevent.html">QMouseEvent</a> *e );
251 void contentsMouseMoveEvent( <a href="qmouseevent.html">QMouseEvent</a> *e );
252 void contentsContextMenuEvent( <a href="qcontextmenuevent.html">QContextMenuEvent</a> *e );
253
254 private:
255 <a href="qcanvasitem.html">QCanvasItem</a> *m_movingItem;
256 <a href="qpoint.html">QPoint</a> m_pos;
257 ElementVector *m_elements;
258 };
259</pre>
260<p> We need to subclass <a href="qcanvasview.html">QCanvasView</a> so that we can handle:
261<ol type=1>
262<li> Context menu requests.
263<li> Form resizing.
264<li> Users dragging labels to arbitrary positions.
265</ol>
266<p> To support these we store a pointer to the canvas item that is being
267moved and its last position. We also store a pointer to the element
268vector.
269<p> <h3> Supporting Context Menus
270</h3>
271<a name="3-1"></a><p> (Extracts from <tt>canvasview.cpp</tt>.)
272<p>
273
274<pre> <a name="x2584"></a>void CanvasView::<a href="qscrollview.html#contentsContextMenuEvent">contentsContextMenuEvent</a>( <a href="qcontextmenuevent.html">QContextMenuEvent</a> * )
275 {
276 <a name="x2579"></a> ((ChartForm*)<a href="qobject.html#parent">parent</a>())-&gt;optionsMenu-&gt;exec( QCursor::<a href="qcursor.html#pos">pos</a>() );
277 }
278</pre>
279<p> When the user invokes a context menu (e.g. by right-clicking on most
280platforms) we cast the canvas view's parent (which is the chart form)
281to the right type and then exec()ute the options menu at the cursor
282position.
283<p> <h3> Handling Resizing
284</h3>
285<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 )
286 {
287 <a name="x2583"></a> <a href="qcanvasview.html#canvas">canvas</a>()-&gt;resize( e-&gt;<a href="qresizeevent.html#size">size</a>().width(), e-&gt;<a href="qresizeevent.html#size">size</a>().height() );
288 ((ChartForm*)<a href="qobject.html#parent">parent</a>())-&gt;drawElements();
289 }
290</pre>
291<p> To resize we simply resize the canvas that the canvas view is
292presenting to the width and height of the form's client area, then
293call drawElements() to redraw the chart. Because drawElements() draws
294everything relative to the canvas's width and height the chart is
295drawn correctly.
296<p> <h3> Dragging Labels into Position
297</h3>
298<a name="3-3"></a><p> When the user wants to drag a label into position they click it, then
299drag and release at the new position.
300<p> <pre> <a name="x2586"></a>void CanvasView::<a href="qscrollview.html#contentsMousePressEvent">contentsMousePressEvent</a>( <a href="qmouseevent.html">QMouseEvent</a> *e )
301 {
302 <a name="x2580"></a> <a href="qcanvasitemlist.html">QCanvasItemList</a> list = <a href="qcanvasview.html#canvas">canvas</a>()-&gt;collisions( e-&gt;<a href="qmouseevent.html#pos">pos</a>() );
303 <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 )
304 if ( (*it)-&gt;rtti() == CanvasText::CANVAS_TEXT ) {
305 m_movingItem = *it;
306 m_pos = e-&gt;<a href="qmouseevent.html#pos">pos</a>();
307 return;
308 }
309 m_movingItem = 0;
310 }
311</pre>
312<p> When the user clicks the mouse we create a list of canvas items that
313the mouse click "collided" with (if any). We then iterate over this
314list and if we find a <tt>CanvasText</tt> item we set it as the moving item
315and record its position. Otherwise we set there to be no moving item.
316<p> <pre> <a name="x2585"></a>void CanvasView::<a href="qscrollview.html#contentsMouseMoveEvent">contentsMouseMoveEvent</a>( <a href="qmouseevent.html">QMouseEvent</a> *e )
317 {
318 if ( m_movingItem ) {
319 <a href="qpoint.html">QPoint</a> offset = e-&gt;<a href="qmouseevent.html#pos">pos</a>() - m_pos;
320 <a name="x2582"></a><a name="x2581"></a> m_movingItem-&gt;moveBy( offset.<a href="qpoint.html#x">x</a>(), offset.<a href="qpoint.html#y">y</a>() );
321 m_pos = e-&gt;<a href="qmouseevent.html#pos">pos</a>();
322 ChartForm *form = (ChartForm*)<a href="qobject.html#parent">parent</a>();
323 form-&gt;setChanged( TRUE );
324 int chartType = form-&gt;chartType();
325 CanvasText *item = (CanvasText*)m_movingItem;
326 int i = item-&gt;index();
327
328 (*m_elements)[i].setProX( chartType, item-&gt;x() / canvas()-&gt;width() );
329 (*m_elements)[i].setProY( chartType, item-&gt;y() / canvas()-&gt;height() );
330
331 <a href="qcanvasview.html#canvas">canvas</a>()-&gt;update();
332 }
333 }
334</pre>
335<p> As the user drags the mouse, move events are generated. If there is a
336moving item we calculate the offset from the last mouse position and
337move the item by this offset amount. We record the new position as the
338last position. Because the chart has now changed we call setChanged()
339so that the user will be prompted to save if they attempt to exit or
340to load an existing chart or to create a new chart. We also update the
341element's proportional x and y positions for the current chart type to
342the current x and y positions proportional to the width and height
343respectively. We know which element to update because when we create
344each canvas text item we pass it the index position of the element it
345corresponds to. We subclassed <a href="qcanvastext.html">QCanvasText</a> so that we could set and get
346this index value. Finally we call update() to make the canvas redraw.
347<p> <center><table cellpadding="4" cellspacing="2" border="0">
348<tr bgcolor="#f0f0f0">
349<td valign="top">A <a href="qcanvas.html">QCanvas</a> has no visual representation. To see the contents of a
350canvas you must create a <a href="qcanvasview.html">QCanvasView</a> to present the canvas. Items only
351appear in the canvas view if they have been show()n, and then, only if
352<a href="qcanvas.html#update">QCanvas::update</a>() has been called. By default a QCanvas's background
353color is white, and by default shapes drawn on the canvas, e.g.
354<a href="qcanvasrectangle.html">QCanvasRectangle</a>, <a href="qcanvasellipse.html">QCanvasEllipse</a>, etc., have their fill color set to
355white, so setting a non-white brush color is highly recommended!
356</table></center>
357<p> <p align="right">
358<a href="tutorial2-05.html">&laquo; Presenting the GUI</a> |
359<a href="tutorial2.html">Contents</a> |
360<a href="tutorial2-07.html">File Handling &raquo;</a>
361</p>
362<p>
363<!-- eof -->
364<p><address><hr><div align=center>
365<table width=100% cellspacing=0 border=0><tr>
366<td>Copyright &copy; 2007
367<a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a>
368<td align=right><div align=right>Qt 3.3.8</div>
369</table></div></address></body>
370</html>
Note: See TracBrowser for help on using the repository browser.