Home > Software engineering >  Qt 4.8 how to do get properties of a QPushButton placed in a QList<QWidget *>?
Qt 4.8 how to do get properties of a QPushButton placed in a QList<QWidget *>?

Time:02-13

Do someone know a solution to do get properties of a QPushButton placed in a QList<QWidget *> ?

.h
QList<QWidget *> list;

.cpp
QPushButton *button = new QPushButton("Push", this);
list->append(button);
qDebug() << list.at(0)->text(); // Not working : text() is not a property of QWidget but a property of QPushButton

Thx

CodePudding user response:

The problem is more to do with c and polymorphism in general rather than anything specific to Qt. The expression...

list.at(0)

returns a QWidget *. Hence the call...

list.at(0)->text()

fails to compile as QWidget has no member function named text. If you think the pointer returned by list.at(0) points to a specific subclass of QWidget then you need to downcast it and check the result before using it. e.g.

if (auto *b = dynamic_cast<QPushButton *>(list.at(0)))
    qDebug() << b->text();

Alternatively -- since you are using Qt -- you can make use of qobject_cast in a similar fashion...

if (auto *b = qobject_cast<QPushButton *>(list.at(0)))
    qDebug() << b->text();
  • Related