Creating user interface code
It's often asked how the user interface is built in KMess. Delightfully, all interfaces are be designed with drag&drop using Qt designer! It stores the designed user interface in a .ui file. The C++ code to create the user interface will be generated automatically from this .ui file. :-)
To include a .ui file to the project, add it's filename to src/CMakeLists.txt. The next time the project is build it, the code from the .ui file will be converted to C++ code automatically.
Loading .ui files
The standard base class to create a dialog is KDialog. To fill it with our widgets, we create a derived class which inherits both KDialog and the generated UI class.
In the header file, the generated code needs to be loaded:
#include <KDialog>
#include "ui_mydialog.h" // generated from mydialog.ui
class MyDialog : public KDialog, private UI::MyDialog
{
Q_OBJECT
public:
MyDialog( QWidget *parent = 0 );
};
The code of the constructor will look like this:
MyDialog::MyDialog( QWIdget *parent )
: KDialog( parent )
, UI:MyDialog()
{
// Setup a main widget with the designed dialog
QWidget *mainWidget = new QWidget( this );
setupUI( mainWidget );
setMainWidget( mainWidget );
}
Key points:
- The constructor initializes it's base class, and the inherited UI::MyDialog which was generated from the mydialog.ui file.
- The KDialog needs a QWidget to use as main widget, so we create it first.
- The created mainWidget object is created with this as parameter, so it becomes a child of the current object and will be deleted automatically.
- Finally, the setupUI() call creates all widgets and populates the mainWidget with them.
Handling widget events
In the designer you can define the methods (slots) which handle the events (signals) from the widgets. After the slots have been defined, you can connect a signal from a widget to one of the slots.
The slot becomes a virtual method in the generated C++ code. In the sub class, you can overwrite this method to implement the action for the event. Such code could look like:
#include <KDialog>
#include "ui_mydialog.h"
class MyDialog : public KDialog, private UI::MyDialog
{
Q_OBJECT
public:
MyDialog( QWidget *parent = 0 );
private slots:
void slotOkButtonClicked();
};
