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
The problem is more to do with
c++ and polymorphism in general rather than anything specific to
Qt. The expression…
QWidget *. Hence the call…
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();
Answered By – G.M.
Answer Checked By – Terry (BugsFixing Volunteer)