KHello #3 - Adding Buttons




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.
/************* khello.h *******************/
#include <kapp.h>
#include <ktmainwindow.h>
#include <qpushbutton.h>

class KHello : public KTMainWindow
{
  Q_OBJECT
public:
  KHello();
  void closeEvent(QCloseEvent *);
public slots:
  void slotHello();
  void slotExit();
private:
  QPushButton *btnHello;
  QPushButton *btnExit;
};


/************* khello.cc ******************/
#include "khello.moc"
#include <kmsgbox.h>

KHello::KHello() : KTMainWindow()
{
  btnHello = new QPushButton("Hello", this);
  btnHello->setGeometry(45,30,50,25);
  btnHello->show();
  connect(btnHello, SIGNAL(clicked()), this, SLOT(slotHello()));
  
  btnExit = new QPushButton("Exit", this);
  btnExit->setGeometry(105,30,50,25);
  btnExit->show();
  connect(btnExit, SIGNAL(clicked()), this, SLOT(slotExit()));  
}

void KHello::closeEvent(QCloseEvent *)
{
  kapp->quit();
}

void KHello::slotHello()
{
  KMsgBox::message(0,"Important","Hello World!");
}

void KHello::slotExit()
{
  close();
}

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

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

[<< Prev] [Next >>]


Daniel Marjamäki
2000-02-01