KDE programming tutorial using KDevelop

Part 5: Enhancing the canvas


[<< Contents] [<< Prev] [Next >>]

Enhancing the canvas

We want to achieve two things in this part. Firstly to control the canvas so it does not go below some minimum size, and secondly to enable the canvas view to update the status bar text.

The minimum size for the canvas will be controlled by two private variables in our CanvasView class. To provide convenient access to the status bar, the CanvasView class will setup a private pointer.

Updating CanvasView

canvasview.h

Add two private variables to store the minimum canvas height and width, two constant to provide the initial minimum height and width, and a pointer to provide convenient access to the status bar.

private:
  KStatusBar*          sbar;                       // shortcut to KSimulate's statusbar
  int                  minCanvasW;                 // minimum canvas width
  int                  minCanvasH;                 // minimum canvas height
  static const int     MIN_CANVAS_W = 350;         // initial canvas minimum width
  static const int     MIN_CANVAS_H = 200;         // initial canvas minimum height

canvasview.cpp

Include kstatusbar.h for access to the status bar functionality.

#include <kstatusbar.h>

In the constructor initialise the private pointer and minimum canvas height and width.

  // set statusbar shortcut
  sbar = parent->statusBar();
  
  // set initial minimum canvas size
  minCanvasW = MIN_CANVAS_W;
  minCanvasH = MIN_CANVAS_H;

Replace the code in the viewportResizeEvent method to ensure the canvas size is never set smaller than the minimum size and to update the status bar text.

  int w = event->size().width();
  int h = event->size().height();
  if ( w < minCanvasW ) w = minCanvasW;
  if ( h < minCanvasH ) h = minCanvasH;

  // resize canvas
  canvas()->resize( w, h );

  // update status bar to say resize happened
  sbar->message(QString("Canvas resized to %1,%2").arg(w).arg(h));

Compile and run

The new code will be compiled automatically when you next attempt to re-run the application using KDevelop. Investigate how the application behaves.


[<< Contents] [<< Prev] [Next >>]


Last updated 14-Dec-2004