pyqt5qt5qsignalmapper

Try to understand QSignalMapper with custom Object


I am trying to understand the QSignalMapper. I got how to map a button click with the slot that handles str. I was trying to map a QObject to do the same, but it keeps failing. Am I doing something wrong or did I miss understanding something ?

class TObject(QObject):
    def __init__(self):
        super().__init__(None)


class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setLayout(QVBoxLayout())

        fruit_list = ["apples", "oranges", "pears"]
        sigMapper = QSignalMapper(self)
        sigMapper.mapped[str].connect(self.SLOTSTR)  # type:ingore
        sigMapper.mapped[TObject].connect(self.SLOTOBJECT)  # type:ingore

        for i, fruit in enumerate(fruit_list):
            btn = QPushButton(fruit)
            btn.clicked.connect(sigMapper.map)
            sigMapper.setMapping(btn, TObject() if i == 0 else str(fruit))
            self.layout().addWidget(btn)

    def SLOTSTR(self, s: str):
        print("SLOTSTR", s)

    def SLOTOBJECT(self):
        print("SLOTOBJECT")

Solution

  • I just figured out the error.

    sigMapper.setMapping(btn, TObject() if i == 0 else str(fruit))
    

    to

    sigMapper.setMapping(btn, TObject(self) if i == 0 else str(fruit))