Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Context Menu : lambda triggered connect - called with same args?



  • I am attempting to build a context menu programmatically and connecting them too.

    I thought I am passing unique arguments to my handler but when I print out the values, they all seems to be given the same arguments when I print them out in the function createInstance(). What am I doing wrongly in the loop ?

        def createInstance(self, category: str, classname: str):
            print('000000000000000000000 createInstance {}:{}'.format(category,classname))
            # self.scene().addNode(category, classname, xpos = 0, ypos = 0, node_id = None)
    
        def createContextMenu(self):
            menu = QtWidgets.QMenu()
            for k, v in self.scene().nodeManager.getClasses().items():
                submenu = menu.addMenu(k)
                for kk, vv in v.items():
                    print('createContextMenu {}:{}'.format(k,kk))
                    action = submenu.addAction(kk)
    
                    # C++ version : https://stackoverflow.com/questions/42522136/qaction-triggered-signal-to-pass-parameter-to-slot
                    # connect(copyDataAction, &QAction::triggered, this, [=](){
                    # CopyTableData(DataTable);
                    # });
    
                    # PySide2 implementation : https://www.pythonguis.com/tutorials/pyside-transmitting-extra-data-qt-signals/
                    action.triggered.connect(lambda x: self.createInstance(k, kk))
    
            return menu
    

  • Lifetime Qt Champion

    Use a parameter with default values as explained here.


  • Lifetime Qt Champion

    Hi,

    k and kk (you should use proper variable names) are not captured so they keep the last value they were assigned.



  • @SGaist Thanks for the advice.

    How do I ensure that they are captured, I cannot use string literal as I would not know in advanced what they will be.

    Cheers


  • Lifetime Qt Champion

    Use a parameter with default values as explained here.



  • @SGaist Thank you for the link. I have got it working.


Log in to reply