views:

648

answers:

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.)

+7  A: 

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.

Karol Wilk
A: 
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