Search code examples
c++qtqobjectqtwidgets

Access QT Widget child members from QT Widget Object Instance


Consider this QWidget initialized as:

QWidget *Logger;
Logger = new QWidget();

QPushButton *btn;
btn= new QPushButton(Logger);
btn->setObjectName(QStringLiteral("pushButton"));

Logger->show();

It display the Logger with a button with text pushButton.
Now Later if i want to access pushButton, i do it like this:

QPushButton *pushButton = Logger->findChild<QPushButton *>("pushButton");
pushButton->setText("NEW BUTTON");

I want to know is there a possibility to access directly this pushButton from Logger??
Something like:

Logger->btn ... 

I tried but it does not work. I have Widgets defined like this with many child objects and i wonder is this the only way to access them at run time??

EDIT: @drescherjm, So something along these lines you mean:

class MyWidget : QWidget
{

public:
    QPushButton *pushButton;
    MyWidget(){
        pushButton = new QPushButton(this);
    }
};


MyWidget *w = new MyWidget();
w->pushButton->setText("XYZ");

And is it worth it to create so many classes?? for small redundant tasks?


Solution

  • It won't work the way that you are expecting it to work. Use btn as long as it is in scope.

    If you are creating btn somewhere locally, but your use-case demands you to use it in different places across your code, then you need to reconsider your design and make the QPushButton part of a class member.

    Something of this sort :

    #include <QPushButton>
    
    class SampleWidget : public QWidget
    {
       public :
         SampleWidget( QWidget * inParent );
         // public methods to change the properties of the QPushButton go here.
         void SetButtonText( QString const & inString );
         bool IsButtonChecked();
    
       private :
         QPushButton *mSampleButton;
    };
    

    And in the implementation :

    SampleWidget::SampleWidget(QWidget *parent)
      :
       mSampleButton( new QPushButton( parent ) )
    {
       // connect( mSampleButton,......... ); Connection to slot
    }
    
    void SampleWidget::SetButtonText( QString const & inString )
    {
       mSampleButton->setText( inString );
    }
    
    bool
    SampleWidget::IsButtonChecked()
    {
       return mSampleButton->isChecked();
    }
    

    The question was not very clear on what you exactly want, but it seems like you are struggling to understand how to alter the attributes of a push button if it is a private member of a class and the above example will help you with that.