The K Desktop Environment

Next Previous Table of Contents

13. Adding Printing Functionality

In this chapter we will show you how easy it is to implement printing functions using Qt. Itīs actually just one line of code for us to do here, but we will start understanding who is actually doing the printing job. When the user presses the print button in KScribble or chooses "Print" from the "File" menu, the slotFilePrint() method is called in KScribbleApp. This method detects which child window is currently activ and creates a printer instance of the class QPrinter. Then it calls the widgetīs printing method, KScribbleView::print(). Here, the framework already contains the base implementation - which already shows you that for printing you just have to use QPainter which then draws on the printer. This method also calls the printing dialog.

What we have to do here is to use QPainter methods to draw the pixmap of the document connected to the view. As QPainter already offers a whole set of methods drawPixmap(), we will of course use one of them:


void KScribbleView::print(QPrinter *pPrinter)
{
  if (pPrinter->setup(this))
  {
    QPainter p;
    p.begin(pPrinter);
                
    ///////////////////////////////
    // TODO: add your printing code here
->      p.drawPixmap(0,0,doc->buffer);
    ///////////////////////////////
    p.end();
  }
}

Here, we paint into the offset of the printer page at 0,0 with our buffer pixmap of the document. Thatīs all !

You can just go ahead and test it - now you can print any graphics that KScribble is able to open.

This is now the end of our trour through creating a KDE 2 application. You can find the source package of KScribble completely with an extension that adds cut, copy, paste and undo functions as well as dragīn drop here:

$(KDEDIR)/share/apps/kdevelop/examples/kscribble-1.0.tar.gz The example tarball is locally installed and can be downloaded to your home directory, where you can untar it and test it. After untarring the tarball with tar zxvf kscribble-1.0.tar.gz, load the project and call "Automake and autoconf" from the "Build" menu in KDevelop, then call "./configure" from the same menu. The configure options are those of my installtion of the KDE 2 and Qt 2.1, so you have to change them manually to match your installation path for these options.

The appendix also contains the complete sourcecode for this package to read through online.

Next Previous Table of Contents