Skip to content

Using lambda with pyqt signals

I wanted to share another great usage for the lambda keyword when working with PyQt in addition to more popular extra arguments use case.

I used the lambda 'trick' to add a custom context menu to a table header in a QTableWidget.

The following snippet is a brief example of using a lambda 'function' to pass the screen position of a right-click operation alongside the triggered signal. This position is then used inside of a QTableWidget to detect which row/column were clicked on.

def _addContextMenu(self):
    header_item.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
    header_item.customContextMenuRequested.connect(self.showContextMenu)

def showContextMenu(self, position):
    deselect_others = QtGui.QAction("Deselect &others", self)
    deselect_others.triggered.connect(lambda: self.deselectOthers(position))

    menu = QtGui.QMenu()
    menu.addAction(deselect_others)
    menu.exec_(self.sender().mapToGlobal(position))

def deselectOthers(self, position):
    print self.indexAt(position).row()
    print self.indexAt(position).column()