Python Forum
[PyQt] locating a pushbutton py its name
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] locating a pushbutton py its name
#1
Hi

I wish to retrieve a pushbutton by its name. I suppose I have to use the function

QfindChild(parent,name)

in a code like the following :

from PyQt5.QtWidgets import QPushButton
class Courriel(QtWidgets.QWidget):
	def __init__(self):
		super(Courriel,self).__init__()
	def init(self, Fenster)
		liste = ['b1',…]
		for item in liste :
			btn=QPushButton(item)
			btn.setObjectName('name'+item)
			…

Fenster=QtWidgets.QWidget()
myCourriel=Courriel()
myCourriel.init(Fenster)
item='my button'
myButton=QfindChild(myCourriel,'name+item)
…
.

Please, can somebody inform me on which module I have to import .

Thanks

Arbiel
using Ubuntu 22.04.5 LTS, Python 3.10.12
having substituted «https://www.lilo.org/fr/» to google, «https://protonmail.com/» to any other unsafe mail service and bépo to azerty (french keyboard layouts)
Reply
#2
You can use findChild

from PyQt5.QtWidgets import (QMainWindow, QApplication, QVBoxLayout, 
                             QWidget, QPushButton, QToolBar, QLabel)

class mainWin(QMainWindow):
    def __init__(self, parent = None):
        super(mainWin, self).__init__(parent)
        self.setupUI()
        
    def setupUI(self):
        self.setGeometry(0, 0, 600, 400)
        central_widget = QWidget()
        vbox = QVBoxLayout()
        
        self.lbl = QLabel()
        vbox.addWidget(self.lbl)
        
        toolbar = QToolBar()
        self.addToolBar(toolbar)
        
        liste = ['b1', 'b2']
        for item in liste :
            btn=QPushButton(item)
            btn.setObjectName(f'name{item}')
            toolbar.addWidget(btn)
        
        central_widget.setLayout(vbox)
        self.setCentralWidget(central_widget)
        
        ### find all buttons
        btn_list = []
        for btn in self.findChildren(QPushButton):
            print(btn.objectName())
            btn_list.append(btn.objectName())
        
        self.lbl.setText(f"Button Names: {', '.join(btn_list)}")
        
        ### find by name
        my_btn = self.findChild(QPushButton, "nameb2")
        if my_btn:
            my_btn.setText("hello world")


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win = mainWin()
    win.setWindowTitle("Main Window")
    win.show()

    sys.exit(app.exec_())
Reply
#3
You could do this:
from PySide6 import QtWidgets


class ButtonGroup(QtWidgets.QWidget):
    def __init__(self, buttons: list[str]):
        super().__init__()
        layout = QtWidgets.QHBoxLayout(self)
        for text in buttons:
            button = QtWidgets.QPushButton(text)
            button.setObjectName(text)
            layout.addWidget(button)


button_names = ["Accept", "Cancel"]
button_groups = ["group1", "group2"]
app = QtWidgets.QApplication()
main_window = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(main_window)
for name in button_groups:
    group = ButtonGroup(button_names)
    group.setObjectName(name)
    layout.addWidget(group)

for name in button_groups:
    group = main_window.findChild(ButtonGroup, name)
    print("Group", group)
    for name in button_names:
        button = group.findChild(QtWidgets.QPushButton, name)
        print("Button", button, button.text())
main_window.show()
app.exec()
If you give each pushbutton a unique name you can do this:
from PySide6 import QtWidgets
 
 
class ButtonGroup(QtWidgets.QWidget):
    def __init__(self, object_name):
        super().__init__()
        self.setObjectName(object_name)
        accept = QtWidgets.QPushButton("Accept")
        accept.setObjectName(f"{object_name}.accept")
        cancel = QtWidgets.QPushButton("Cancel")
        cancel.setObjectName(f"{object_name}.cancel")
        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(accept)
        layout.addWidget(cancel)
 

class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        group1 = ButtonGroup("group1")
        group2 = ButtonGroup("group2")
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(group1)
        layout.addWidget(group2)

app = QtWidgets.QApplication()
main_window = MainWindow()

accept1 = main_window.findChild(QtWidgets.QPushButton, "group1.accept")
cancel2 = main_window.findChild(QtWidgets.QPushButton, "group2.cancel")
print(accept1, accept1.text())
print(cancel2, cancel2.text())

main_window.show()
app.exec()
findChild will dive down into button groups and look at all the push buttons.

But why use names? The code is much cleaner if you reference objects directly instead of looking them up by name. Make the buttons attributes of the instance, and use the instance name to reference the objects.
from PySide6 import QtWidgets


class ButtonGroup(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.accept = QtWidgets.QPushButton("Accept")
        self.cancel = QtWidgets.QPushButton("Cancel")
        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(self.accept)
        layout.addWidget(self.cancel)


class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.groups = [ButtonGroup() for _ in range(2)]
        layout = QtWidgets.QVBoxLayout(self)
        for group in self.groups:
            layout.addWidget(group)


app = QtWidgets.QApplication()
main_window = MainWindow()
layout = QtWidgets.QVBoxLayout(main_window)
for group in main_window.groups:
    print(group, group.accept, group.accept.text())
    print(group, group.cancel, group.cancel.text())
main_window.show()
app.exec()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGUI] Pushbutton in ANSA Aishaf 2 4,611 Apr-27-2021, 11:22 AM
Last Post: Aishaf
  [PyQt] pushbutton with image issac_n 1 2,836 Jul-13-2020, 05:04 PM
Last Post: Knight18
  [PyQt] Add command to PushButton skaailet 1 2,852 Apr-11-2020, 01:46 PM
Last Post: deanhystad
  TypeError when using PushButton (PyQt5) lmsavk 1 9,575 Mar-03-2019, 04:21 PM
Last Post: Alfalfa
  pyqt clickable pushbutton problem pythonck 1 9,372 Dec-12-2017, 03:38 PM
Last Post: pythonck
  keeping track of pushbutton click iFunKtion 3 6,149 Mar-13-2017, 12:18 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020