Luke Lee

Software Engineer

Web + Desktop + Science

Fork me on Github

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):

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

        menu = QtGui.QMenu()

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

Published: 06-18-2012 20:11:00