How to check whether a widget is in a layout? I have a layout that may contain the widget or not.
- Widget name:
infoClient - Layer name:
verticalLayout_3
Need to check if the widget exists in the layout, then do not add a new one.
And if does not exist, add a new one.
How to do it?
void MainWindow::slotPush1()
{
if <there is no infoClient> ui->verticalLayout_3->addWidget(new infoClient(this));
}
Use QObject::findChild to find a child by its name. For instance:
Note: findChild is a template function. If you’re not familiar with template functions, just know that you pass the type of object you want to find (in your example, it looks like you could use
ui->verticalLayout_3->findChild<infoClient*>("infoClient")). If you want to find a QWidget, or anything that inherits from QWidget, you can just usefindChild<QWidget*>()and you’ll be safe.