Andre
Andre

Reputation: 51

How to add qwidget to qlist<qwidget>

I have several widgets, like

QLineEdit           m_namePoiFilter;
QLineEdit           m_ID_MSSIPoiFilter;

I would like to add them to a list of qwidgets, then set all of them visible.

I have made

QList<QWidget>      m_PoiFilterWidgets;

but I can not add an item to it like

m_PoiFilterWidgets.push_back(m_namePoiFilter);

Upvotes: 1

Views: 1059

Answers (2)

You need to hold these via a pointer, and you should use a lower-overhead container like std::array. E.g.:

class Foo {
   QLineEdit m_namePoiFilter;
   QLineEdit m_ID_MSSIPoiFilter;
   std::array<QLineEdit*, 2> const m_edits = {&m_namePoiFilter, &m_ID_MSSIPoiFilter};
};

This code is safe from dangling pointers by construction: m_edits will be constructed after the widgets are constructed, and will be destroyed before the widgets are destroyed: thus its contents are always valid.

I'd avoid QList/QVector as these allocate on the heap - unnecessarily in your case.

Upvotes: 1

owacoder
owacoder

Reputation: 4873

QObjects, from which QWidgets are defined, are non-copyable. This means that you must store them in a list as pointers to widgets (i.e. QList<QWidget *>).

Upvotes: 0

Related Questions