summaryrefslogtreecommitdiffstats
path: root/doc/html/tutorial2-06.html
blob: baf5493c65fa3e8ec3b6484b332b92d7fdbae84d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<!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&nbsp;Classes</font></a>
 | <a href="mainclasses.html">
<font color="#004faf">Main&nbsp;Classes</font></a>
 | <a href="annotated.html">
<font color="#004faf">Annotated</font></a>
 | <a href="groups.html">
<font color="#004faf">Grouped&nbsp;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">TQCanvasItemList</a> list = m_canvas-&gt;allItems();
        for ( TQCanvasItemList::iterator it = list.<a href="ntqvaluelist.html#begin">begin</a>(); it != list.<a href="ntqvaluelist.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; TQt works with 16ths of degrees
        int scaleFactor = m_chartType == PIE ? 5760 :
                            m_chartType == VERTICAL_BAR ? m_canvas-&gt;height() :
                                m_canvas-&gt;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 &lt; MAX_ELEMENTS; ++i ) {
            if ( m_elements[i].isValid() ) {
                double value = m_elements[i].value();
                count++;
                total += value;
                if ( value &gt; biggest )
                    biggest = value;
                scales[i] = m_elements[i].value() * scaleFactor;
            }
        }

        if ( count ) {
                // 2nd loop because of total and biggest
            for ( int i = 0; i &lt; 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-&gt;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
TQt 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-&gt;width();
        double height = m_canvas-&gt;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="ntqpen.html">TQPen</a> pen;
    <a name="x2575"></a>    pen.<a href="ntqpen.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 &lt; 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">TQCanvasRectangle</a> *rect = new <a href="qcanvasrectangle.html">TQCanvasRectangle</a>(
                                                0, y, extent, proheight, m_canvas );
    <a name="x2572"></a>            rect-&gt;<a href="qcanvaspolygonalitem.html#setBrush">setBrush</a>( TQBrush( m_elements[i].valueColor(),
                                        BrushStyle(m_elements[i].valuePattern()) ) );
    <a name="x2573"></a>            rect-&gt;<a href="qcanvaspolygonalitem.html#setPen">setPen</a>( pen );
    <a name="x2570"></a>            rect-&gt;<a href="qcanvasitem.html#setZ">setZ</a>( 0 );
    <a name="x2571"></a>            rect-&gt;<a href="qcanvasitem.html#show">show</a>();
</pre>
<p> We create a new <a href="qcanvasrectangle.html">TQCanvasRectangle</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="ntqstring.html">TQString</a> label = m_elements[i].label();
    <a name="x2576"></a>            if ( !label.<a href="ntqstring.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 &lt; 0 || proY &lt; 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 &lt; 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-&gt;<a href="qcanvastext.html#setColor">setColor</a>( m_elements[i].labelColor() );
    <a name="x2568"></a>                text-&gt;<a href="qcanvasitem.html#setX">setX</a>( proX * width );
    <a name="x2569"></a>                text-&gt;<a href="qcanvasitem.html#setY">setY</a>( proY * height );
                    text-&gt;<a href="qcanvasitem.html#setZ">setZ</a>( 1 );
                    text-&gt;<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">TQCanvasText</a>
</h2>
<a name="2"></a><p> (Extracts from <tt>canvastext.h</tt>.)
<p> 

<pre>    class CanvasText : public <a href="qcanvastext.html">TQCanvasText</a>
    {
    public:
        enum { CANVAS_TEXT = 1100 };

        CanvasText( int index, TQCanvas *canvas )
            : <a href="qcanvastext.html">TQCanvasText</a>( canvas ), m_index( index ) {}
        CanvasText( int index, const <a href="ntqstring.html">TQString</a>&amp; text, TQCanvas *canvas )
            : <a href="qcanvastext.html">TQCanvasText</a>( text, canvas ), m_index( index ) {}
        CanvasText( int index, const <a href="ntqstring.html">TQString</a>&amp; text, TQFont font, TQCanvas *canvas )
            : <a href="qcanvastext.html">TQCanvasText</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">TQCanvasText</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">TQCanvasView</a>
</h2>
<a name="3"></a><p> (Extracts from <tt>canvasview.h</tt>.)
<p> 

<pre>    class CanvasView : public <a href="qcanvasview.html">TQCanvasView</a>
    {
        <a href="metaobjects.html#Q_OBJECT">Q_OBJECT</a>
    public:
        CanvasView( <a href="ntqcanvas.html">TQCanvas</a> *canvas, ElementVector *elements,
                    <a href="ntqwidget.html">TQWidget</a>* parent = 0, const char* name = "canvas view",
                    WFlags f = 0 )
            : <a href="qcanvasview.html">TQCanvasView</a>( canvas, parent, name, f ), m_movingItem(0),
              m_elements( elements ) {}

    protected:
        void viewportResizeEvent( <a href="qresizeevent.html">TQResizeEvent</a> *e );
        void contentsMousePressEvent( <a href="qmouseevent.html">TQMouseEvent</a> *e );
        void contentsMouseMoveEvent( <a href="qmouseevent.html">TQMouseEvent</a> *e );
        void contentsContextMenuEvent( <a href="qcontextmenuevent.html">TQContextMenuEvent</a> *e );

    private:
        <a href="qcanvasitem.html">TQCanvasItem</a> *m_movingItem;
        <a href="ntqpoint.html">TQPoint</a> m_pos;
        ElementVector *m_elements;
    };
</pre>
<p> We need to subclass <a href="qcanvasview.html">TQCanvasView</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="ntqscrollview.html#contentsContextMenuEvent">contentsContextMenuEvent</a>( <a href="qcontextmenuevent.html">TQContextMenuEvent</a> * )
    {
    <a name="x2579"></a>    ((ChartForm*)<a href="ntqobject.html#parent">parent</a>())-&gt;optionsMenu-&gt;exec( TQCursor::<a href="ntqcursor.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="ntqscrollview.html#viewportResizeEvent">viewportResizeEvent</a>( <a href="qresizeevent.html">TQResizeEvent</a> *e )
    {
    <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() );
        ((ChartForm*)<a href="ntqobject.html#parent">parent</a>())-&gt;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="ntqscrollview.html#contentsMousePressEvent">contentsMousePressEvent</a>( <a href="qmouseevent.html">TQMouseEvent</a> *e )
    {
    <a name="x2580"></a>    <a href="qcanvasitemlist.html">TQCanvasItemList</a> list = <a href="qcanvasview.html#canvas">canvas</a>()-&gt;collisions( e-&gt;<a href="qmouseevent.html#pos">pos</a>() );
    <a name="x2589"></a><a name="x2588"></a>    for ( TQCanvasItemList::iterator it = list.<a href="ntqvaluelist.html#begin">begin</a>(); it != list.<a href="ntqvaluelist.html#end">end</a>(); ++it )
            if ( (*it)-&gt;rtti() == CanvasText::CANVAS_TEXT ) {
                m_movingItem = *it;
                m_pos = e-&gt;<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="ntqscrollview.html#contentsMouseMoveEvent">contentsMouseMoveEvent</a>( <a href="qmouseevent.html">TQMouseEvent</a> *e )
    {
        if ( m_movingItem ) {
            <a href="ntqpoint.html">TQPoint</a> offset = e-&gt;<a href="qmouseevent.html#pos">pos</a>() - m_pos;
    <a name="x2582"></a><a name="x2581"></a>        m_movingItem-&gt;moveBy( offset.<a href="ntqpoint.html#x">x</a>(), offset.<a href="ntqpoint.html#y">y</a>() );
            m_pos = e-&gt;<a href="qmouseevent.html#pos">pos</a>();
            ChartForm *form = (ChartForm*)<a href="ntqobject.html#parent">parent</a>();
            form-&gt;setChanged( TRUE );
            int chartType = form-&gt;chartType();
            CanvasText *item = (CanvasText*)m_movingItem;
            int i = item-&gt;index();

            (*m_elements)[i].setProX( chartType, item-&gt;x() / canvas()-&gt;width() );
            (*m_elements)[i].setProY( chartType, item-&gt;y() / canvas()-&gt;height() );

            <a href="qcanvasview.html#canvas">canvas</a>()-&gt;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">TQCanvasText</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="ntqcanvas.html">TQCanvas</a> has no visual representation. To see the contents of a
canvas you must create a <a href="qcanvasview.html">TQCanvasView</a> to present the canvas. Items only
appear in the canvas view if they have been show()n, and then, only if
<a href="ntqcanvas.html#update">TQCanvas::update</a>() has been called. By default a TQCanvas's background
color is white, and by default shapes drawn on the canvas, e.g.
<a href="qcanvasrectangle.html">TQCanvasRectangle</a>, <a href="qcanvasellipse.html">TQCanvasEllipse</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">&laquo; Presenting the GUI</a> |
<a href="tutorial2.html">Contents</a> |
<a href="tutorial2-07.html">File Handling &raquo;</a>
</p>
<p> 
<!-- eof -->
<p><address><hr><div align=center>
<table width=100% cellspacing=0 border=0><tr>
<td>Copyright &copy; 2007
<a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a>
<td align=right><div align=right>TQt 3.3.8</div>
</table></div></address></body>
</html>