2

How do I make a QVector (or some other container class) of a dynamic number of widgets, such as QPushButton or QComboBox in Qt 4?

I've used the following in my window class's constructor:

QVector<QComboBox*> foo; // Vector of pointers to QComboBox's

And now I want to fill it with some number of controls which can change dynamically:

for(int count = 0; count < getNumControls(); ++count) {
    foo[count] = new QComboBox();
}

I've searched for hours trying to find the answer to this. The Qt forums mention making a QPtrList, but that class no longer exists in Qt4. I'd later try to get the text value from each using array-style indexing or the .at() function.

I would really appreciate an example of declaring, initializing, and populating any data structure of any QWidgets (QComboBox, QPushButton, etc.)

ymoreau
  • 3,402
  • 1
  • 22
  • 60
Charles Burns
  • 10,310
  • 7
  • 64
  • 81

2 Answers2

10

here you go :)

#include <QWidget>
#include <QList>
#include <QLabel>
...
QList< QLabel* > list;
...

list << new QLabel( parent, "label 1" );
..
..

foreach( QLabel* label, list )  {
label->text();
label->setText( "my text" );
}

If you are trying just to get a simple example to work, its important that your widgets have a parent (for context / clean up) purposes.

Hope this helps.

bgs
  • 1,210
  • 10
  • 19
  • I wanted to insert combo-boxes from the .ui file into a list. I inserted this way: `QList listComboBox;` `listComboBox << (ui->comboBoxTitle);` and retrieved like this: `QComboBox *comboBox = listComboBox.at(i);` which is working all fine! : ) – zeFree Jan 23 '13 at 04:29
  • QVector is now preferred to QList ([read more](https://stackoverflow.com/a/38263633/6165833)). – ymoreau Aug 22 '17 at 09:00
0
foo[count] = new QComboBox();

This won't affect the size of foo. If there isn't already an item at index count, this will fail. See push_back, or operator<<, which add an item to the end of the list.

QVector<QComboBox*> foo;
// or QList<QComboBox*> foo;
for(int count = 0; count < getNumControls(); ++count) {
    foo.push_back(new QComboBox());
    // or foo << (new QComboBox());
}

Later, to retrieve the values:

foreach (QComboBox box, foo)
{
  // do something with box here
}
Bill
  • 14,257
  • 4
  • 43
  • 55