简体   繁体   中英

Retrieving QPushButton from QWidget

I have a QPushButton with related icon, and I add it to a scene:

QPushButton *button = new QPushButton;
button->setIcon(QIcon(myIcon));
buttonWidget = detail->scene()->addWidget(button);
// buttonWidget is declared globally and is a QGraphicsProxyWidget*

Later on, in a different function, the buttonWidget is still accessible. How can I retrieve the QPushButton object from the buttonWidget ? I would like to change its icon.

也许您可以使用QGraphicsProxyWidget::widget来获取基础的QWidget* ,然后使用dynamic_cast转换为QPushButton*

QPushbutton *otherButton = dynamic_cast<QPushButton*>(buttonWidget->widget());

You can retrieve the object as a QWidget using QGraphicsProxyWidget::widget and then casting to a QPushButton .

But I'd recommand to make the QPushButton be an attribute of your class (always better that casting). Then you access it later whenevr you want.

button = new QPushButton; // declare button as an attribute of your class in the header file
button->setIcon(QIcon(myIcon));
buttonWidget=detail->scene()->addWidget(button);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM