Search code examples
qtqwidget

How to get the text on qpushbutton?


I am loading .ui files via QUiloader, and showing the GUI in my application.

QWidget *mywidget = loader.load(file, this);
QList<QWidget*> wlist = mywidget.findChildren<QWidget *>()

I would like to know what is the text on QPushbutton. I know there is a method text() to get a text from Pushbutton, but it is not accessible when I do:

QString btext = wlist.at(1).text();

Any idea how I can get the text from QPushbutton, and other Widgets, when they grouped as QWidget?

Thanks.


Solution

  • You should search for QPushButtons instead of QWidgets:

    QList<QPushButton*> blist = widget.findChildren<QPushButton*>();
    

    Still your code wouldn't compile. The last line should read:

    QString btext = blist.at(1)->text();
    

    Using -> since you are accessing a pointer, not the widget. Also you should check if the findChildren() function actually returnes enough buttons. You would get a crash or assertions when accessing a list item by an invalid index.

    Also please note that at(1) does not return the first but the second item in the list (lists start from 0).

    Update: If you search for QWidgets and cast each of them you need to take care of getting a nullptr:

    QList<QWidget*> wlist = widget.findChildren<QWidget*>();
    foreach (QWidget* w, wlist)
    {
       QPushButton* b = dynamic_cast<QPushButton*>(w);
       // If "w" is not a button "b" is nullptr
       if (b)
       {
          QString btext = b->text();
       }
    }