PyQt5 – Adding action to ComboBox with checkable items
In this article we will see how we can add a action to the combo box who have check-able items. By default when we create a combo box its items are not check-able i.e we can select any one item at a time although we can create such combo box by editing the combo box class. Below is the representation of how check-able combo box look like.
In order to do this we have to make a new editable combo box class which inherits the combo box and adds a new feature of check able combo box. Below is the syntax of new class and have to add a method when combo box get checked.
# new check-able combo box class CheckableComboBox(QComboBox): # constructor def __init__(self, parent=None): super(CheckableComboBox, self).__init__(parent) self.view().pressed.connect(self.handleItemPressed) self.setModel(QStandardItemModel(self)) count = 0 # action called when item get checked def do_action(self): window.label.setText("Checked number : " +str(self.count)) # when any item get pressed def handleItemPressed(self, index): # getting the item item = self.model().itemFromIndex(index) # checking if item is checked if item.checkState() == Qt.Checked: # making it unchecked item.setCheckState(Qt.Unchecked) # if not checked else: # making the item checked item.setCheckState(Qt.Checked) self.count += 1 # call the action self.do_action()
Below is the implementation
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course