Search code examples
pythonqcombobox

How do I get the name of the QCombobox which is triggering def onCurrentIndexChanged(self, index):


I have two Qcomboboxes in my Ui_MainWindow. How do I determine which of them is triggering the def onCurrentIndexChanged(self, index):??? When I printed self.class.name it returns "Ui_MainWindow"...I want the name of the Qcombobox within that window???

def onCurrentIndexChanged(self, index):
   
    print(self.__class__.__name__)
    id_ = self.cboDebtor.itemData(index, IdRole)
    # or
    # id_ = self.model.item(index).data(IdRole)

Solution

  • Assuming you have a method connected to a slot, you can use self.sender() inside that method to retrieve the widget that sent the signal.

    So if you want to display the name of the widget which sent the signal, do it like this:

    def onCurrentIndexChanged(self, index):
        print(self.sender().objectName())
    

    Given your description, you probably want to do something like:

    def onCurrentIndexChanged(self, index):
        sender_name = self.sender().objectName()
        if sender_name == 'foo':  # QComboBox 1's name
            self.do_something()
        elif sender_name == 'bar':  # QComboBox 2's name
            self.do_something_else()
        # etc