Development/Tutorials/Printing Print Dialog

< Development‎ | Tutorials
Revision as of 20:54, 29 June 2011 by Neverendingo (Talk | contribs) (Text replace - "</code>" to "</syntaxhighlight>")

Jump to: navigation, search

The mission

To display the Print Dialog and print a document.

KDE uses the Qt Printing infrastructure, but adds extra standard features to the Print Dialog, as well as allowing applications to add their own extensions.

The code

 1 #include <QtGui/QPainter>
 2 #include <QtGui/QPrinter>
 3 
 4 #include <KdePrintDialog>
 5 #include <KPrintPreview>
 6 
 7 #include <KApplication>
 8 #include <KAboutData>
 9 #include <KCmdLineArgs>
10 
11 /*
12 This prints Hello World on your printer
13 */
14 
15 int main(int argc, char *argv[])
16 {
17     KAboutData aboutData( "test", "test", "1.0", "test",
18                           KAboutData::License_GPL, "(c) 2006" );
19     KCmdLineArgs::init( argc, argv, &aboutData );
20     KApplication app;
21 
22     KAction* m_printPreview = KStandardAction::printPreview(app, SLOT(slotFilePrintPreview()), actionCollection());
23 
24     KHelloWorldPrintDialogWidget optionsWidget;
25 
26     QPrinter printer;
27     printer.setFullPage(true);
28     QPrintDialog *printDialog = KdePrint::createPrintDialog(&printer, QList<QWidget*>() << &yourOptionsWidget, this);
29     printDialog.setWindowTitle(i18n("Print Hello World"));
30     if (printDialog.exec()) {
31         QPainter painter;
32         painter.begin(&printer);
33         painter.drawText(100,100,"Hello World");
34         if (optionsWidget.printMoreText()) {
35         }
36         painter.end(); 
37         // this makes the print job start
38     }
39 }
40 
41 class KHelloWorldPrintDialogWidget : public QWidget
42 {
43     bool printMoreText();
44     void setPrintMoreText(bool state);
45 
46     setWindowTitle(i18n("Your Options Tab Title"));
47 }
48 
49 void KHelloWorld::slotFilePrintPreview() {
50     QPrinter printer;
51     KPrintPreview printPreview(&printer);
52     yourPrintDrawingRoutine(printer); // draws to the QPrinter
53     printPreview.exec();
54 }

How to compile

CMakeLists.txt

find_package(KDE4 REQUIRED)
include_directories( ${KDE4_INCLUDES} )
kde4_add_executable(printhelloworld printtest.cpp)
target_link_libraries(printhelloworld ${${KDE4_KDECORE_LIBS} ${KDE4_KUTILS_LIBS} ${QT_QTGUI_LIBRARY})

Make and Run

Then do:

cmake .
make
./printhelloworld