Reputation: 657
For example in the code below:
>>> from PyQt5.QtWidgets import *
>>> import sys
>>> app = QApplication(sys.argv)
>>> widget = QWidget()
>>> layout = QVBoxLayout()
>>> push_button = QPushButton("Hello")
>>> layout.addWidget(push_button)
>>> widget.setLayout(layout)
>>> push_button
<PyQt5.QtWidgets.QPushButton object at 0x7f52d2427700>
>>>
I would like to have access to <PyQt5.QtWidgets.QPushButton object at 0x7f52d2427700>
from the widget object. Is it possible ?
Upvotes: 1
Views: 549
Reputation: 120598
When widgets are added to a layout, they will be automatically re-parented to the widget that subsequently contains the layout. This means you can use findChild to get a reference to any child in the tree of objects below a given root widget. This works best if you give the target object a name:
>>> push_button.setObjectName('btn_hello')
>>> widget.findChild(QPushButton, 'btn_hello').text()
'Hello'
If the target object doesn't have a name, findChildren could also be used to search for descendant objects of the same type:
>>> for button in widget.findChildren(QPushButton):
... if button.text() == 'Hello':
... print(button)
... break
...
<PyQt5.QtWidgets.QPushButton object at 0x7fa0e089bb50>
The find methods search recursively by default, but it's also possible to limit the search to direct children only (the returned list is in the order the children were added to the parent):
>>> for text in 'One Two Three'.split():
... layout.addWidget(QPushButton(text))
...
>>> widget.findChildren(QPushButton, options=Qt.FindDirectChildrenOnly)[1].text()
'One'
To search for child objects of different types, a tuple of types can be used:
>>> for text in 'Red Blue Green'.split():
... layout.addWidget(QLabel(text))
...
>>> widget.findChildren((QLabel, QPushButton))[4].text()
'Red'
Upvotes: 2