loop over QLabel Attributes?
-
Hi
I need to have a row of checkboxes (23) with numbering QLabels above.
I created a QGridLayout and put all the QLabel's in the first row and all
QCheckBox'es in the second row.
As you can see the numbers above are not perfectly centered over the individual checkboxes. I found that I can center each label by setting theQLabel::setAlignment(Qt::AlignCenter)
for each label, but this is a LOAD of code for 23 labels:
label0->setAlignment(Qt::AlignCenter); label1->setAlignment(Qt::AlignCenter); label2->setAlignment(Qt::AlignCenter); ... label23->setAlignment(Qt::AlignCenter);
Is it somehow possible to loop over the labels and set the alignment
with a simple for loop or so? -
If you want to get all QLabel in one form you can use QWidget::findChildren()
-
@pauledd
Put your labels into an array/vector, and iterate through that to access them. This will be useful for all sorts of operations. By the time you have that many items it's "usual" to access them by array instead of having each one have its own variable, though you can still keep individual variables if you wish, just copy them into an array/vector as well for when you want to loop over them.P.S.
You can also do @Christian-Ehrlicher's way for dynamic finding, and/or also useQObject::setObjectName()
on each one. I still suspect you ought have an array/vector of them anyway. -
@pauledd if this is the only thing you want to do with it, I would recommend doing the legwork and writing it all down.
It should enable the compiler to do more optimizations.
However you can use https://doc.qt.io/qt-5/qobject.html#findChildren
to loop over all children of a widget, and then use qobject_cast<QLabel*>() to check if the child is a QLabel or not.
Make sure to select the correct "parent widget" or you may end up finding other QLabels where you do not want to change the property.
Also findChildren is a rather costly execution, its probably fine during startup, but I would recommend not to use it during runtime of your program.
-
@J-Hilk said in loop over QLabel Attributes?:
Also findChildren is a rather costly execution, its probably fine during startup, but I would recommend not to use it during runtime of your program.
@pauledd
...which is why even if you use that you probably want to end up putting them into an array... -
Thanks a lot for your suggestions. I ended up doing it with the vectors because it was most elegant for my brain...
*.h
QVector<QLabel*> labels;
*.cpp
for(int i=0;i<24;i++){ labels.append(new QLabel(QString::number(23-i))); } for(int i=0;i<labels.size();i++){ labels[i].setAlignment(Qt::AlignCenter); }
and then the same for the checkboxes. I guess the vector saved about 100 lines of code.
Works like a charm :)