Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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.


  • Lifetime Qt Champion

    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..


  • Lifetime Qt Champion

    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 not QApplication::instance()'s child, unless you have set the parent to be it.
    You could use QApplication::allWidgets() or QApplication::topLevelWidgets() to iterate widgets of the application, but still not a good design.



  • @Bonnie
    Thanks for your answer!


Log in to reply