It is possible to find a child if we know its type and name (if specified) like this:
QPushButton *button = parentWidget->findChild<QPushButton *>("button1");
However each QObject
has metaObject()
function property which returns QMetaObject*
. In its turn QMetaObject
has function className()
. Is it possible to easily find QObject
by class name like this:
QWidget *widget = (QWidget*)parentWidget->findByClassName("QPushButton", "button1");
Or the only way to get all QWidget
children by
QList<QWidget *> widgets = parentWidget->findChildren<QWidget *>("widgetname");
and then filter the list with std::find_if
by metaObject()->className()
?
findChild()
already allows you to specify the type of what you are searching for.
The second parameter is actually the objectName
string property.
If you are asking whether you can specify the class type as string, there doesn't appear to be such an option.
You could easily make such function, simply iterate the object tree and query the each object's meta object for the class name and compare against your string.
QObject * findByClassName(const QObject * const o, const char *name) {
QObject * res = nullptr;
foreach (QObject * c, o->children()) {
if (res) break;
if (QLatin1String(c->metaObject()->className()) == name) res = c;
else res = findByClassName(c, name);
}
return res;
}
And then simply findByClassName(parentWidget, "QPushButton")
, obviously, you can expand on this to include the objectName
and do some qobject_cast
ing if you want to get the pointer as a concrete type... which if you did, you simply should have used the existing findChild()
function anyway... Specifying the type as a string only makes sense when you don't know the type in advance, and it is say... determined during the runtime.