Customing widgets (subclassing)

Sometimes there are situations where we need to override some methods or add new methods/signal/slots to the widgets (i.e. when adding drag & drop capability). We'll show how to do this with Designer (and eventually without it :-).

Launch Designer and create new widget. Put Tree Widget there. Add some items and subitems by right clicking and choosing Edit Items.

Vertical layout is applied to the form. Name it myFormDLG (objectName).

Save form as myform.ui. You will also need main.cpp, as well as a myqtapp.cpp and myqtapp.h. Make application work. See My first Qt GUI application if you forgot.

If you are ready with application, Right click treeWidget and choose Promote to Custom Widget. Choose custom class name (myTreeWidget). Save form.

If you now try to build application, you'll get:

ui_myform.h:11:26: mytreewidget.h: No such file or directory
... more errors here

Right, we need to define mytreewidget.h and mytreewidget.cpp files which are actually definition and implementation our customized treeWidget.


#include <QtGui>
class myTreeWidget : public QTreeWidget
    myTreeWidget(QWidget *parent = 0);


#include "mytreewidget.h"
myTreeWidget::myTreeWidget(QWidget *parent)
    : QTreeWidget(parent)

Do not forget to add mytreewidget.h and mytreewidget.cpp to your .pro file and re-run qmake to update makefiles.

You can add your method/signal/slots or override existing ones.

Project ready: