Search code examples
pythonpyqtqcombobox

How to set a default task from a list of options in a QComboBox?


EDITED

I have two options in my QComboBox which are "feet" and "meters". The app crashes(python stopped working) each time I select the first option on the GUI or if I proceed without selecting any of the two since the value is in "feet" already.

I have the following edited lines of code;

from PyQt5 import QtCore, QtWidgets

class Widget(QtWidgets.QWidget):
def __init__(self):
    super().__init__()

    self.value = QtWidgets.QLineEdit()
    self.unit = QtWidgets.QComboBox()
    self.convert = QtWidgets.QPushButton()

    self.setLayout(QtWidgets.QVBoxLayout())

    self.value.setObjectName("value")
    self.layout().addWidget(self.value)

    self.layout().addWidget(self.unit)
    self.unit.addItems(["feet", "meters"])

    self.layout().addWidget(self.convert)
    self.convert.setText("Convert")

    self.unit.currentIndexChanged.connect(self.unit_select)
    self.convert.clicked.connect(self.convert_click)

# UNIT SELECT
def unit_select(self):
    current_index = self.unit.currentIndex()
    if current_index == 0:
        num = float(self.value.text()) * 0.3047972654
    elif current_index == 1:
        num = float(self.value.text()) * 1
    self.final = num

# CONVERT VALUE
def convert_click(self):
    print("Converted value =", self.final)



if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

I need to set "feet" as the default of the QComboBox.


Solution

  • Try it:

    from PyQt5 import QtCore, QtWidgets
    
    class Widget(QtWidgets.QWidget):
        def __init__(self):
            super().__init__()
    
            self.unit = QtWidgets.QComboBox()
    
            self.setLayout(QtWidgets.QVBoxLayout())
            self.layout().addWidget(self.unit)
            self.unit.addItems(["feet", "meters"])
    
            self.unit.setCurrentIndex(0)                            # <-----
            self.current_index = 0                                  # <-----
    
            self.unit.activated[int].connect(self.onActivatedIndex)
            self.unit.currentIndexChanged.connect(self.unit_select)
    
            self.unit_select(self.current_index)
    
        @QtCore.pyqtSlot(int)
        def onActivatedIndex(self, index):
            print("ActivatedIndex", index)
    
        @QtCore.pyqtSlot(int)
        def unit_select(self, index):
    
            if index == 0:
                print("\nCurrentIndex {} - feet".format(index))
                # ...
            elif index == 1:
                print("\nCurrentIndex {} - meters".format(index))
                # ...            
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())
    

    enter image description here


    Update:

    import re      # To test string conversion to float  !!!
    
    from PyQt5 import QtCore, QtWidgets
    
    class Widget(QtWidgets.QWidget):
        def __init__(self):
            super().__init__()
    
            self.value   = QtWidgets.QLineEdit()
            self.unit    = QtWidgets.QComboBox()
            self.convert = QtWidgets.QPushButton()
    
            self.setLayout(QtWidgets.QVBoxLayout())
    
            self.value.setObjectName("value")
            self.layout().addWidget(self.value)
    
            self.layout().addWidget(self.unit)
            self.unit.addItems(["feet", "meters"])
    
            self.layout().addWidget(self.convert)
            self.convert.setText("Convert")
    
            self.unit.currentIndexChanged.connect(self.unit_select)
            self.convert.clicked.connect(self.convert_click)
    
        # UNIT SELECT
        def unit_select(self):
    
            if re.match("^\d+?\.*\d*?$", self.value.text()) is None: #self.value.text():
                QtWidgets.QMessageBox.information(None, 'Warning', 
                    'The string QLineEdit `{}` cannot be converted to float'.format(self.value.text()))
                return False            
    
            current_index = self.unit.currentIndex()
            if current_index == 0:
                num = float(self.value.text()) * 0.3047972654
            elif current_index == 1:
                num = float(self.value.text()) * 1
            self.final = num
    
        # CONVERT VALUE
        def convert_click(self):
    
            if re.match("^\d+?\.*\d*?$", self.value.text()) is None: #self.value.text():
                QtWidgets.QMessageBox.information(None, 'Warning', 
                    'The string QLineEdit `{}` cannot be converted to float'.format(self.value.text()))
            else:
                self.unit_select()
                print("Converted value =", self.final)
    
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())
    

    enter image description here