Search code examples
pythoncomboboxpyqt5

Pass the value of currentTextChanged


Following is a piece of code.

Currently the combobox is managed by self.Cbox.btn.clicked.connect(self.Goto_Analyze).

I would like to avoid the btn and use currentTextChanged but wherever I put it I get an error.

    self.MyCbox = QtWidgets.QComboBox(self.My_tab)
    self.MyCbox.setGeometry(QtCore.QRect(700, 30, 100, 21))
    self.MyCbox.setObjectName("MyCbox")
    self.MyCbox.addItems(Functions.nbr)
    
    aa  = str(self.MyCbox.currentText())
    print(aa) # aa = 6
    self.Cbox.btnsetText(_translate("Library_main", "Select"))
    self.Cbox.btnclicked.connect(self.Goto_Analyze)
    


def Goto_Analyze(self, ): 
        aa = str(self.MyCbox.currentTextChanged())
        [...]
        some code


File "../index.py", line 796, in Goto_Analyze
aa = str(self.MyCbox.currentTextChanged())
TypeError: native Qt signal is not callable

Solution

  • It is signal so you need

    currentTextChanged.connect(...)
    

    like for signal clicked you need clicked.connect(...)


    Minimal working code

    from PyQt5 import QtWidgets
    
    class MyWindow(QtWidgets.QWidget):
        
        def __init__(self, parent=None):
            super().__init__(parent)
    
            
            self.cbox = QtWidgets.QComboBox(self)  # PEP8: `lower_case_name` for variables
            self.cbox.addItems([str(x) for x in range(3)])
    
            self.cbox.currentTextChanged.connect(self.goto_analyze)
    
        def goto_analyze(self, value):  # PEP8: `lower_case_name` for functions
            print(type(value), value)
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication([])
        win = MyWindow()
        win.show()
        app.exec()
    

    PEP 8 -- Style Guide for Python Code