Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple widgets into one in Qt

Tags:

c++

widget

qt

I'm repeatedly using a pair of QComboBox and QListWidget 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.

like image 448
Donotalo Avatar asked Dec 03 '11 08:12

Donotalo


1 Answers

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

class CustomWidget: public QWidget {
 Q_OBJECT

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

 private:
  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.

like image 114
Mat Avatar answered Oct 04 '22 04:10

Mat