0

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")
Ansh David
  • 654
  • 1
  • 10
  • 26
  • 1
    Note that QSignalMapper is a very old class that was required when it wasn't possible to use lambdas in Qt slots. While it still exists, it's rarely used, and is mostly considered obsolete. In python this is actually not even an issue, and that class is not really required: you can just use functools.partial, lambdas, or custom signals. – musicamante May 26 '22 at 09:51
  • thanks. using `partial` makes a lot of sense and keeps things simple – Ansh David Jun 09 '22 at 16:00

1 Answers1

0

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))
Ansh David
  • 654
  • 1
  • 10
  • 26