dynamically unknown size of label array
Hi,
I'm a newbie for Qt C++. I want to create the QLabels Array programmatically.
It's ok. code is as follow:
Code:
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QLabel>
{
Q_OBJECT
public:
~MyWidget();
private:
};
#endif // MYWIDGET_H
Code:
#include "mywidget.h"
#include <QLabel>
#include <QVBoxLayout>
MyWidget
::MyWidget(QWidget *parent
){
int i;
for(i=0;i<5;i++)
{
layout->addWidget(mylabel[i]);
}
this->setLayout(layout);
}
This code created 5 label
But I want to create labels that numbers is assigned when I call class.
My Question is how to assign number of labels to create dynamically?
just example:
Code:
#include "mywidget.h"
int main(int argc, char *argv[])
{
MyWidget mytitle(3); // create 3 labels
MyWidget mysubtitle(10); // create 10 labels
return 0;
}
Another Question is Array can resize and created programmatically.
I created it in VB just like:
Code:
dim A() as string
.....
ReDim A(1)
Dim i as Integer
i = UBound(A) + 1
ReDim Preserve A(i)
If yes, how to do it?
Thanks in advance.
Re: dynamically unknown size of label array
(1) Make the number of labels a parameter of MyWidget ctor:
Code:
{
Q_OBJECT
public :
MyWidget
( int howmany,
QWidget *parent
= 0 );
...
};
then you can use the syntax shown in your post.
(2) Use QVector<MyWidget *> instead of a "plain" array. You'll be able to resize or remove existing vector items.
Re: dynamically unknown size of label array
thanks for your replay.
eg. how to assign parameter (eg howmany) as array size?
I change code as follow: It gives error.
Code:
{
Q_OBJECT
public:
MyWidget
(int howmany,
QWidget *parent
= 0);
~MyWidget();
private:
int n;
};
#endif // MYWIDGET_H
Code:
#include "mywidget.h"
#include <QLabel>
#include <QVBoxLayout>
MyWidget
::MyWidget(int howmany,
QWidget *parent
){
int i;
for(i=0;i<n;i++)
{
layout->addWidget(mylabel[i]);
}
this->setLayout(layout);
}
compiler give error:
mywidget.h:39: error: invalid use of non-static data member 'MyWidget::n'
int n;
^
Re: dynamically unknown size of label array
Don't use an array. Use QVector or QList as Radek said. Both of them don't need initial size.
Re: dynamically unknown size of label array
Thanks Radek and Lesiok.
I changed from array to QList. I got it.
Re: dynamically unknown size of label array
(1) The error: You cannot declare a "plain" array with a variable size
Code:
private:
int n;
QLabel *mylabel
[n
];
// compile error
Tne n needed be an initialized const int.
(2) IMO, QVector is better here. QVector is a dynamic array while QList is a linked list. Nevertheless both of them will serve you good.
Re: dynamically unknown size of label array
QList is not a linked list, but I agree that QVector is more appropriate here since the length is already known at creation time.
Cheers,
_