Development/Tutorials/KDE2/KHello/Tutorial 3

< Development‎ | Tutorials‎ | KDE2‎ | KHello
Jump to: navigation, search

Description

Now is the time to add a few buttons.

Source code

The old code is gray. I have not included main.cc below, because it is the same as in KHello #2.

 1 /************* khello.h *******************/
 2 #include <kapp.h>                 // From KHello2
 3 #include <kmainwindow.h>          // From KHello2
 4 #include <qpushbutton.h>
 5 
 6 class KHello : public KMainWindow // From KHello2
 7 {                                 //  |
 8   Q_OBJECT                        //  |
 9 public:                           // From KHello2
10   KHello();
11   void closeEvent(QCloseEvent *); // From KHello2
12 public slots:
13   void slotHello();
14   void slotExit();
15 private:
16   QPushButton *btnHello;
17   QPushButton *btnExit;
18 };
 1 /************* khello.cc ******************/
 2 #include "khello.moc"             // From KHello2
 3 #include <kmessagebox.h>
 4 
 5 KHello::KHello() : KMainWindow()
 6 {
 7   btnHello = new QPushButton("Hello", this);
 8   btnHello->setGeometry(45,30,50,25);
 9   btnHello->show();
10   connect(btnHello, SIGNAL(clicked()), this, SLOT(slotHello()));
11   
12   btnExit = new QPushButton("Exit", this);
13   btnExit->setGeometry(105,30,50,25);
14   btnExit->show();
15   connect(btnExit, SIGNAL(clicked()), this, SLOT(slotExit()));  
16 }
17 
18 void KHello::closeEvent(QCloseEvent *e) // From KHello2
19 {                                       //  |
20   kapp->beep();                         //  |
21   KMainWindow::closeEvent(e);           //  |
22 }                                       // From KHello2
23 
24 void KHello::slotHello()
25 {
26   KMessageBox::messageBox(0, KMessageBox::Information, "Hello World!");
27 }
28 
29 void KHello::slotExit()
30 {
31   close();
32 }

Explaining the code

I'll only explain what I believe is necessary this time.

public slots:

This section is new, and it used by the meta object compiler. In the QT world, slots are event-handlers and signals are events. Put all your event handlers in this section.

connect(btnHello, SIGNAL(clicked()), this, SLOT(slotHello()));

Connect the event "clicked" from the btnHello object to the event handler "slotHello".

Compiling

[on linux where KDEDIR and QTDIR contain the paths to where KDE and Qt are installed respectively] [FreeBSD 5.x users may omit the -ldl]

g++ -c -I$KDEDIR/include -I$QTDIR/include -fno-rtti main.cc
moc khello.h -o khello.moc
g++ -c -I$KDEDIR/include -I$QTDIR/include -fno-rtti khello.cc
g++ -L$KDEDIR/lib -L$QTDIR/lib -lkdeui -lkdecore -lqt -ldl -o khello main.o khello.o

[if moc is not in your path try $QTDIR/bin/moc]


This page was last modified on 29 June 2011, at 20:52. Content is available under Creative Commons License SA 3.0 as well as the GNU Free Documentation License 1.2 unless otherwise noted.