How do I create a QVector widget?
How do I create QVector
(or some other container class) a dynamic number of widgets like QPushButton
or QComboBox
in Qt 4?
In my window class constructor, I used the following:
QVector<QComboBox*> foo; // Vector of pointers to QComboBox's
And now I want to fill it with some number of controls that 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 question. The Qt forums mention creation QPtrList
, but this class no longer exists in Qt4. Later I will try to get the text value from each using array style indexing or function .at()
.
I would really like an example of declaring, initializing and filling any data structure with any QWidgets
( QComboBox
, QPushButton
etc.)
source to share
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're just trying to get a simple example to work with, it's important that your widgets have parent (for context / cleanup) purposes.
Hope it helps.
source to share
foo[count] = new QComboBox();
This will not affect the size of foo. If there is no item in the index, this will fail. See push_back or operator << , which add an element 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 get the values:
foreach (QComboBox box, foo)
{
// do something with box here
}
source to share