0

I want to call a method when a button is pressed using clicked.connect() . Method should simply output text inside the clicked button.

import sys
from PyQt5.QtCore import QSize, QSignalMapper 
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QGridLayout, QWidget

class MainWindow(QMainWindow):    
    def __init__(self):

        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(300, 200))    

        grid = QGridLayout()
        buttons = []
        positions = [(i,j) for i in range(10) for j in range(5)]
        print('\npostions: ', positions)

        for i in range(200):
            buttons.append('Button '+str(i)) 

        signalMapper = QSignalMapper(self)
        i = 0

        for position, buttons in zip(positions, buttons):            
            print('\npostion, buttons: ', position, buttons)
            button = QPushButton(buttons, self)
            signalMapper.setMapping(button, buttons)
            button.clicked.connect(signalMapper.map)
            grid.addWidget(button, *position)

        signalMapper.mapped.connect(self.getResults)
        print('\nsignalMapper.map:', signalMapper.map)

        widget = QWidget()
        widget.setLayout(grid)
        self.setCentralWidget(widget)      

This method should call when a button is clicked.

def getResults(self, button):
    signals = MainWindow.button.text()
    print('\nsignals:\n', signals)

Here is my main method.

if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())

What's wrong? How do I have to use this signalmapper?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
sticki
  • 43
  • 1
  • 8
  • on the line `for position, buttons in zip(positions, buttons):`, you use `buttons` as the unpacked version of the list `buttons`. Start by fixing that. – David Culbreth Mar 18 '20 at 18:14
  • I recommend avoid irrelevant phrases. – eyllanesc Mar 18 '20 at 18:15
  • 1) Pay attention to what I point you to DavidCulbreth as it can cause problems but in this case luckily you do not. 2) If you are mapping the text then the mapped signal should send the text and not the button so you must change to `signalMapper.mapped[str].connect(self.getResults)` and `def getResults(self, button): signals = MainWindow.button.text() print('\nsignals:\n', signals)` to `def getResults(self, signals): print('\nsignals:\n', signals)` – eyllanesc Mar 18 '20 at 18:23
  • @eyllanesc thank you very much. Now is everything fine. – sticki Mar 19 '20 at 00:18

0 Answers0