Main Window
Author: Jim Bublitz

# Tutorial - Second Program

### KMainWindow

In this tutorial, we turn the simple "Hello, World" program into a full-fledged KDE program (but not one that does anything useful).

Most KDE programs have at least two features in common: the have a main window that manages all of the other elements that make up the graphical interface of the program, and they have an event loop, that handles the communication between the program elements and between the user and the program (mouse clicks and keyboarding).

First, we change the objects we imports from kdeui:

    from PyKDE4.kdeui import KApplication, KMainWindow

We're no longer importing the KGuiItem or KMessageBox we used in the first program.

Next, we create our own customized main window by subclassing (inheriting from) KMainWindow:

    class MainWindow (KMainWindow):
        def __init__ (self):
            KMainWindow.__init__ (self)

When you derive a new class from an existing class, it's important to call the constructor or __init__ of the parent class. In this case, KMainWindow.__init__ doesn't require any arguments, so we just pass self to it.

Notice that our main window (MainWindow) does absolutely nothing but create itself.

In order to display our main window and have our program operate, we add just three lines to the end of our program:

    mainWindow = MainWindow ()
    mainWindow.show ()
    app.exec_ ()

The first line:

    mainWindow = MainWindow ()

creates an instance of our MainWindow class. The next line:

    mainWindow.show ()

causes our main window to be displayed. The final line:

    app.exec_ ()

starts KApplication's event loop. In the previous program we didn't have an event loop running, but the program could still respond to mouse clicks - that's because KDE dialogs run their own private event loop behind the scenes.

Note also that in PyKDE, the call to run the event loop is exec_ - the extra underscore at the end of the name is necessary because otherwise the name would clash with Python's built-in exec keyword.

app.exec_ runs continuously, handling all the events that make up the actions of our program - it doesn't return until program execution ends. Once app.exec_ begins to run, nothing else in our program will occur unless initiated by some event or action, either from the user, some external source, or some event we create, like a timer timing-out.

That means that usually all initialization and setup takes place before we start the event loop.

### What now?

In PyKDE for KDE3, this would be a good start for a complete program. In KDE4, programs operate a little differently, and most probably won't use KMainWindow directly any longer - much of the functionality that was in KMainWindow in KDE3 has been moved into another class. We'll look at that class - KXmlGuiWindow - in the next tutorial.