Search code examples
pythonpyqtpyqt5pyside

how to make dynamically added anonymous buttons, when clicked, execute a function Pyside/Pyqt


I'm trying to understand pyside.

how to make the dynamically added anonymous buttons, when clicked, also execute the add_button function?

in this case, would it be necessary to use the pyside signals?

example.py:


import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2 import QtWidgets


class Template(QWidget):

    def __init__(self):
        super().__init__()
        add_btn = QPushButton('Add')
        add_btn.clicked.connect(self.add_button)

        
        
        
        self.grid = QGridLayout(self)
        self.grid.addWidget(add_btn, 0, 0, 1, 4, Qt.AlignLeft)

    def add_button(self):
        i = self.grid.count() - 1   
        self.grid.addWidget(QPushButton(f'add {i + 1}'), 1 + i // 4, i % 4)
        
        

if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = Template()
    gui.show()
    sys.exit(app.exec_())

thanks.


Solution

  • I know this works in PyQt and I think it also works in PySide. You can pass in the function you want to run as a clicked keyword argument:

    QPushButton('Push me', clicked=self.some_function)