Search code examples
c++qtqwidgetqlist

Accessing QWidget child slots/signals from a QWidgetList (QList<QWidget*>)


I am making a gui app designer. Every time the user create a new widget, it is stored in a QWidgetList. It can be a QPushButton, a QLineEdit, whatever.

For example, let's say I have a QPushButton (index 0) and a QLineEdit (index 1).

Is it possible to access the signal clicked of WidgetList[0], or use the slot setText of WidgetList[1] ?

Or do I really have to make a QList for each type, like QList<QPushButton> and QList<QLineEdit> ?

Thanks in advance


Solution

  • To use the new connect syntax, you have to cast the widgets to correct types. E.g.:

    QPushButton b{“clear”};
    QLineEdit e;
    QWidgetList widgets{&b, &e};
    QObject::connect(qobject_cast<QPushButton*>(widgets[0]), &QPushButton::clicked,
                     qobject_cast<QLineEdit*>(widgets[1]), &QLineEdit::clear);
    

    In a designer use case, you’ll probably be referring to signals and slots using their text signatures or QMetaMethod handles, and then there’s no need for any casting at all, since those connect methods upcast the objects to QObject anyway.