[SOLVED] How to access a not yet created widget
-
Hello
I'm trying to set up some sort of menu where the user is able to add as much widgets to a layout as he wants and to remove them as well. Therefore I create the widget and add it to the layout if the user calls one:
@
myItem = new MyItem();
myLayout->addWidget(myItem);
setLayout(myLayout);
@That works. Now I want to know how many and which widgets are added. This was able with this:
@
for(int i = 0; i < myLayout->count(); i++) {
qDebug() << myLayout->itemAt(i)->widget();
}
@Now let's say, the QWidget Item has a QSpinBox in it. The question is, how can I access e.g. the value of that QSpinBox inside that widget? I mean something like
@
myLayout->itemAt(i)->widget()->mySpinBox->value();
@isn't working because over the widget() command I'm able to access only general QWidget properties.
Thx for any help!
-
Got it:
@
for(int i = 0; i < myLayout->count(); i++) {
qDebug() <<
centralWidget->layout->itemAt(i)->widget()->children()[2]->property("value");
}
@The position of my QSpinBox in myWidget is at position 2. So with this I can access the value of it.
By the way, could this create some sort of problems if I create lots of "myItems" with the same name and add them to the layout? During my little test it worked.
-
Hi!
I had a similar problem.
-
You can use "QMetaObject::invokeMethod":http://qt-project.org/doc/qt-4.8/qmetaobject.html#invokeMethod, which works like reflection and returns true or false if that method exists. You'll need to write a list of possible methods which are used for return values ( text(), value()..., (load them dynamically from a file))
-
Another option, which is more or leas the same as upper, is to use C++11 reflections, if your compiler supports it ( I haven't tried it yet).
-
Every QObject class has user custom dynamic property option ( see "this":http://doc.qt.digia.com/stable/qobject.html#setProperty). You can create enum for classes, add it to property and then cast it to original class in a giant switch.
I'd go with the first option.
I didn't found any solution which would make this easier.Hope it helps.
Regards,
Jake -
-
You can also use "qobject_cast":http://qt-project.org/doc/qt-4.8/metaobjects.html to have a MyItem class and access it