Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions

Canvas Control

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.

(Extracts from chartform_canvas.cpp.)

drawElements()

    void ChartForm::drawElements()
    {
        TQCanvasItemList list = m_canvas->allItems();
        for ( TQCanvasItemList::iterator it = list.begin(); it != list.end(); ++it )
            delete *it;

The first thing we do in drawElements() is delete all the existing canvas items.

            // 360 * 16 for pies; TQt works with 16ths of degrees
        int scaleFactor = m_chartType == PIE ? 5760 :
                            m_chartType == VERTICAL_BAR ? m_canvas->height() :
                                m_canvas->width();

Next we calculate the scale factor which depends on the type of chart we're going to draw.

        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;

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 scales array.

            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;
            }
        }

Now that we have the necessary information we call the relevant drawing function, passing in the scaled values, the total and the count.

        m_canvas->update();

Finally we update() the canvas to make the changes visible.

drawHorizontalBarChart()

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.

    void ChartForm::drawHorizontalBarChart(
            const double scales[], double total, int count )
    {

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.

        double width = m_canvas->width();
        double height = m_canvas->height();
        int proheight = int(height / count);
        int y = 0;

We retrieve the width and height of the canvas and calculate the proportional height (proheight). We set the initial y position to 0.

        TQPen pen;
        pen.setStyle( NoPen );

We create a pen that we will use to draw each bar (rectangle); we set it to NoPen so that no outlines are drawn.

        for ( int i = 0; i < MAX_ELEMENTS; ++i ) {
            if ( m_elements[i].isValid() ) {
                int extent = int(scales[i]);

We iterate over every element in the element vector, skipping invalid elements. The extent of each bar (its length) is simply its scaled value.

                TQCanvasRectangle *rect = new TQCanvasRectangle(
                                                0, y, extent, proheight, m_canvas );
                rect->setBrush( TQBrush( m_elements[i].valueColor(),
                                        BrushStyle(m_elements[i].valuePattern()) ) );
                rect->setPen( pen );
                rect->setZ( 0 );
                rect->show();

We create a new TQCanvasRectangle 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 NoPen) and we place the bar at position 0 in the Z-order. Finally we call show() to draw the bar on the canvas.

                TQString label = m_elements[i].label();
                if ( !label.isEmpty() || 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;
                    }

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).

                    label = valueLabel( label, m_elements[i].value(), total );

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.)

                    CanvasText *text = new CanvasText( i, label, m_font, m_canvas );
                    text->setColor( m_elements[i].labelColor() );
                    text->setX( proX * width );
                    text->setY( proY * height );
                    text->setZ( 1 );
                    text->show();
                    m_elements[i].setProX( HORIZONTAL_BAR, proX );
                    m_elements[i].setProY( HORIZONTAL_BAR, proY );

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.

                }
                y += proheight;

After drawing a bar and possibly its label, we increment y by the proportional height ready to draw the next element.

            }
        }
    }

Subclassing TQCanvasText

(Extracts from canvastext.h.)

    class CanvasText : public TQCanvasText
    {
    public:
        enum { CANVAS_TEXT = 1100 };

        CanvasText( int index, TQCanvas *canvas )
            : TQCanvasText( canvas ), m_index( index ) {}
        CanvasText( int index, const TQString& text, TQCanvas *canvas )
            : TQCanvasText( text, canvas ), m_index( index ) {}
        CanvasText( int index, const TQString& text, TQFont font, TQCanvas *canvas )
            : TQCanvasText( 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;
    };

Our CanvasText subclass is a very simple specialisation of TQCanvasText. All we've done is added a single private member m_index which holds the element vector index of the element associated with this text item, and provided a getter and setter for this value.

Subclassing TQCanvasView

(Extracts from canvasview.h.)

    class CanvasView : public TQCanvasView
    {
        TQ_OBJECT
    public:
        CanvasView( TQCanvas *canvas, ElementVector *elements,
                    TQWidget* parent = 0, const char* name = "canvas view",
                    WFlags f = 0 )
            : TQCanvasView( canvas, parent, name, f ), m_movingItem(0),
              m_elements( elements ) {}

    protected:
        void viewportResizeEvent( TQResizeEvent *e );
        void contentsMousePressEvent( TQMouseEvent *e );
        void contentsMouseMoveEvent( TQMouseEvent *e );
        void contentsContextMenuEvent( TQContextMenuEvent *e );

    private:
        TQCanvasItem *m_movingItem;
        TQPoint m_pos;
        ElementVector *m_elements;
    };

We need to subclass TQCanvasView so that we can handle:

  1. Context menu requests.
  2. Form resizing.
  3. Users dragging labels to arbitrary positions.

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.

Supporting Context Menus

(Extracts from canvasview.cpp.)

    void CanvasView::contentsContextMenuEvent( TQContextMenuEvent * )
    {
        ((ChartForm*)parent())->optionsMenu->exec( TQCursor::pos() );
    }

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.

Handling Resizing

    void CanvasView::viewportResizeEvent( TQResizeEvent *e )
    {
        canvas()->resize( e->size().width(), e->size().height() );
        ((ChartForm*)parent())->drawElements();
    }

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.

Dragging Labels into Position

When the user wants to drag a label into position they click it, then drag and release at the new position.

    void CanvasView::contentsMousePressEvent( TQMouseEvent *e )
    {
        TQCanvasItemList list = canvas()->collisions( e->pos() );
        for ( TQCanvasItemList::iterator it = list.begin(); it != list.end(); ++it )
            if ( (*it)->rtti() == CanvasText::CANVAS_TEXT ) {
                m_movingItem = *it;
                m_pos = e->pos();
                return;
            }
        m_movingItem = 0;
    }

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 CanvasText item we set it as the moving item and record its position. Otherwise we set there to be no moving item.

    void CanvasView::contentsMouseMoveEvent( TQMouseEvent *e )
    {
        if ( m_movingItem ) {
            TQPoint offset = e->pos() - m_pos;
            m_movingItem->moveBy( offset.x(), offset.y() );
            m_pos = e->pos();
            ChartForm *form = (ChartForm*)parent();
            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() );

            canvas()->update();
        }
    }

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 TQCanvasText so that we could set and get this index value. Finally we call update() to make the canvas redraw.

A TQCanvas has no visual representation. To see the contents of a canvas you must create a TQCanvasView to present the canvas. Items only appear in the canvas view if they have been show()n, and then, only if TQCanvas::update() has been called. By default a TQCanvas's background color is white, and by default shapes drawn on the canvas, e.g. TQCanvasRectangle, TQCanvasEllipse, etc., have their fill color set to white, so setting a non-white brush color is highly recommended!

« Presenting the GUI | Contents | File Handling »


Copyright © 2007 TrolltechTrademarks
TQt 3.3.8