Donotalo Donotalo - 3 months ago 33
C++ Question

Combine multiple widgets into one in Qt

I'm repeatedly using a pair of

in a project. Their interaction is highly coupled - when an item is selected in the combo box, the list is filtered in some way. I'm copy pasting all the signal and slot connections between these two widgets across multiple dialog box implementation which I don't think is a good idea.

Is it possible to create a custom widget, which will hold these two widgets and will have all signal and slot connection in one place? Something like as follows:

class CustomWidget
QComboBox combo;
QListWidget list;


I want to use this widget as a single widget.

Mat Mat

The usual way of doing this is to sub-class QWidget (or QFrame).

class CustomWidget: public QWidget {

 CustomWidget(QWidget *parent)
  : QWidget(parent) {
    combo = new QComboBox(...);
    list  = new QListWidget(...);
    // create the appropriate layout
    // add the widgets to it

  QComboBox *combo;
  QListWidget *list;


Handle all the interactions between the list and the combo in that custom widget (by connecting the appropriate signals to the appropriate slots, possibly defining your own slots for this).

You then expose your custom widget's behavior/API through dedicated signals and slots, possibly mimicking the ones in the list and/or the combo.

The Address book tutorial walks you through all of that, including creating a custom widget and defining signals and slots for it.