[Main Page] [KHello #1] [KHello #2] [KHello #3] [KHello #4] [KHello #5]

Hello World - The third effort

We've got a window. We've got a polite titlebar that greets us in a friendly fashion. Now for something a little more interactive - a button. Look - if it's all right with you I'll combine the two files from the previous attempt in one again - we now know how to split our code into separate modules after all.

#!/usr/bin/env python

import sys
from kdeui import KApplication
from kdeui import KTMainWindow
from kdeui import KMsgBox
from kdecore import kapp
from qt import QPushButton
from qt import SIGNAL

class khello(KTMainWindow):
  def __init__(self):
    self.connect(self.hello, SIGNAL("clicked()"), self.slotHello)    

  def slotHello(self):
    KMsgBox.message(self, "Important", "Hello World!")
  def closeEvent(self, QCloseEvent):
app=KApplication(sys.argv, "Hello World!")

We add a button in the __init__ constructor of our khello object. The button is defined as a member of this particular instance, self, otherwise, every instance of the class would use the same button.

The button is hooked up to our class instance with the second parameter - this is necessary because otherwise it wouldn't know in which window to draw itself. A bit of geography shuffling later, we are ready to show it.

A button that doesn't do anything is as much use as, as, as something not useful at all. The Qt toolkit uses the concept of signals and slots to link widgets like buttons with functions that actually do something. This is not too different from events and event-handlers and so on - just a little matter of terminology. The KDE bindings offer full support for this mechanism, as we can see here. A Qt signal is connected to a python function in the line

    self.connect(self.hello, SIGNAL("clicked()"), self.slotHello)    

Whenever the button is clicked, the function slotHello is called. Don't forget the ubiquitous selves, as they are essential. The actual work is done in the function slotHello, which gives us a polite little messagebox.

Since version 0.7 has become available, there have been two changes necessary for this program: the connect function must now be qualified, and the static function to show a messagebox has changed from KMsgBox_message(self, "Important", "Hello World!") to KMsgBox.message(self, "Important", "Hello World!")