How to get a pointer to a specific widget when you know only its name?
-
@J-Hilk Yes it does, so theres no other option than iterating the topLevelWidgets? im trying to get a pointer to the QMainWindow exclusively to get a pointer to a specific widget.
@Ylvy
Yes, if you want to find a top-level window, assuming yourQMainWindowis such, and you are somewhere that does not have access to yourQMainWindow*variable, walk (don't descend)QWidgetList QApplication::topLevelWidgets()for aQMainWindow*. Then use that formainWindow->findChild<YourWidgetClass*>("SpecificWidgetObjectName");I use this for debugging purposes. It may not be a sign of great design if your code really needs to find the main window for this purpose.
-
@Ylvy Why do you need to get the pointer to your main window using the name? Main window does not necessarily have a parent.
Usually you call findChild from the parent (or anywhere higher in the hierarchy) of the widget. -
@jsulm i'm trying to get a
childfrom theQMainWindow, when i know only its name, but i'm trying to avoid passing/saving a pointer to the widget/QMainWindow.@Ylvy said in How to get a pointer to a specific widget when you know only its name?:
i'm trying to get a child from the QMainWindow
No, you don't.
You're trying to get pointer to QMainWindow instance using its name... -
I tried below but its returning null.
QMainWindow* window = QApplication::instance()->findChild<QMainWindow*>("AppClass");QWidget* mainWindow = qApp->activeWindow();work only if the window is active, would not help. -
In addition to what the others said, are you sure, your instance actually has an objectName to look for ? A default object name is only done via QDesigner - plugin.
-
In addition to what the others said, are you sure, your instance actually has an objectName to look for ? A default object name is only done via QDesigner - plugin.
-
@J-Hilk Yes it does, so theres no other option than iterating the topLevelWidgets? im trying to get a pointer to the QMainWindow exclusively to get a pointer to a specific widget.
@Ylvy
Yes, if you want to find a top-level window, assuming yourQMainWindowis such, and you are somewhere that does not have access to yourQMainWindow*variable, walk (don't descend)QWidgetList QApplication::topLevelWidgets()for aQMainWindow*. Then use that formainWindow->findChild<YourWidgetClass*>("SpecificWidgetObjectName");I use this for debugging purposes. It may not be a sign of great design if your code really needs to find the main window for this purpose.
-
Y Ylvy has marked this topic as solved on