Grouping widgets into array
-
Let me sketch the problem a bit.
With the help of Qt Creator I've created a set of QSpinBoxes, QCheckBoxes and QComboBoxes. All QSpinBoxes have a standard name e.g. sb_x where x is the next number in line. And for the sake of the description let's assume that I have 16 of them. Inside code when I'm referring to specific widget I write:@ui->sp_x->setValue(5);@
When I want to set new value to all 16 of them it's getting a bit messy. Is there a way to do this by loop? If so, what else should I do to make it possible?
Please don't say to write the widgets by hand, I mean in code. Yes, then you have the full control over them but it requires some time. Using Qt Creator I just do it fast and it is convenient. I have written a chunk of code in WinAPI and I just don't want to go through it again.
It would be nice if this could work for other widgets. What is important is also the order of the widgets in this array.
-
How about something like this:
@std::vector<QSpinBox *> spins{ui.sp_0, ui.sp_1, ui,sp_2,};
std::for_each(spins.begin(), spins.end(), [](QSpinBox *spn, const double x){ spn->setValue(x); });
@ -
Yes, this can definitely do it. Thanks.
Meanwhile, I have come up with another question. Which is actually a variation of this what I've described at the beginning. Let's say I don't change name of the spin boxes and those have some default names. Not necessary consistent names. Some part of them I have grouped in the frame which is vertically aligned. Is there a way to access the widgets inside the frame in some ordered way.
-
You can find objects by their name using QObject::findChild, and so fill the std::vector<QSpinBox *> by code instead of by hand.
-
Yes, but as you said I have to use findChild and feed it with object's name.
As I've written in my second post the names are random like sb_1, sb_5, sb_7, .... and I have few of theme. The method findChild would force me to rename all of the items.
I found childAt() method which uses coordinates in widget's coordinate system. Unless I'm wrong, it uses "visible" coordinate system. What would actually be a very good solution to what I need is a method which would take exactly the same parameters as childAt() but interpret them as "grid" coordinates. -
Hi,
If you use a QGridLayout to organize your widgets, you can use the itemAtPosition method :
@QLayoutItem * itemAtPosition ( int row, int column ) const;@You will be able to get the corresponding widget thanks to the QLayoutItem::widget() method.
-
Hi,
Just use findChildren<QSpinBox*> and you'll have the list of all QSpinBoxes