Solved How to find a widget through QApplication::instance()?
-
Main_window::Main_window (QWidget *parent) : QMainWindow(parent) { QHBoxLayout *layout = new QHBoxLayout; QPushButton *button = new QPushButton("button"); QPushButton *button2 = new QPushButton("button2"); button->connect(button, &QPushButton::clicked, this, &Main_window::do_something); button2->setObjectName("button2"); layout->addWidget(button); layout->addWidget(button2); this->UI.setupUi(this); this->centralWidget()->setLayout(layout); } void Main_window::do_something () { QPushButton *button2 = QApplication::instance()->findChild<QPushButton *>("button2"); qDebug() << button2; // QWidget(0x0) }
I want to find a widget using findChild() method with QApplication::instance(), but it's not working.
QApplication::instance()->findChild<QPushButton *>("button2");
When I use findChild() method with Main_window's instance, it works well.
this->findChild<QPushButton *>("button2");
Could you tell me why it fails with QApplication::instance(), and how to solve this? Thanks in advance.
-
I don't know exactly why it does not work but also don't understand why you would need it.
-
@Christian-Ehrlicher
I want to access a widget from afar without pass widget as argument.void Main_window::do_something () { for (auto &widget : QApplication::allWidgets()) if (widget->objectName() == "button2") { QPushButton *button2 = static_cast<QPushButton *>(widget); qDebug() << button2; } }
The above solution is working well. It's weird..
-
Looks like no good design.
Please provide a minimal, compileable testcase. -
Not a good design +1.
However, about the question, it's simple, because a widget (or any other QObject) is normally notQApplication::instance()
's child, unless you have set the parent to be it.
You could useQApplication::allWidgets()
orQApplication::topLevelWidgets()
to iterate widgets of the application, but still not a good design. -
@Bonnie
Thanks for your answer!