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

Hello World - fourth version

Originally, this exercise merely added a quit button to the window - not very exciting, I find, so I will pass very lightly over that issue. The next exercise will introduce the adding of menus, so I thought I could as well broach the topic of buttonbars with this exercise.

#!/usr/bin/env python

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

class khello(KTMainWindow):
  def __init__(self):
    self.quit =QPushButton("Quit",self)


    self.connect(self.hello, SIGNAL("clicked()"), self.slotHello)    
    self.connect(self.quit,SIGNAL("clicked()"), self.slotQuit)
    tb = self.toolBar() 

  def slotToolbarClicked(self,item):
    if item == khello.TOOLBAR_EXIT:
  def slotHello(self):
    KMsgBox.message(self, "Important", "Hello World!")
  def slotQuit(self):
  def closeEvent(self, QCloseEvent):
app=KApplication(sys.argv, "Hello World!")

Scanning the code from top to bottom, we first find a constant-like expression, that might be familiar to you if you have already looked at Phil's kmyapp.py example. This is an identifier for the solitary button on our buttonbar.

Because those buttonbars when clicked return an integer that refers to the button clicked, instead of some easily readable identifier, it's handy to keep that identifying integer in the form of a constant.

The only remarkable aspect about our second button, the quit one, is the slot function, slotQuit. It calls the close function of our main window widget, which generates a closeEvent call - and by exercising kapp.quit, our app comes to its end, rather more cleanly than a Norwegian Blue Parrot.

Next a toolbar is defined: tb=self.toolBar(). Yes, we could use self.toolBar() directly, as in the kmyapp.py example which comes with PyKDE, but this seems a bit cleaner. A button is added to the the toolbar, with the KDE standard exit.xpm icon and our old friend the constant as identifier. It is enabled, therefore the literal '1'. Python still has not a true boolean type... Finally, a tooltip text is added, cleverly using the i18n function to assist in localizing our application.

Another possibility would have been to have a separate function called for each button in the toolbar, instead of a handler for all buttons in the toolbar. You must decide which you prefer.

To connect the toolbar click signal to our Python defined slot slotToolbarClicked is not an arduous task, and neither is checking in that function which button was pressed and acting accordingly. The kmyapp.py example has a direct kapp.quit() in this place - something I don't hold with. Only one exit point to my applications, please. Therefore we raise a close event with is handled by our closeEvent handler.