I would like to be able to select multiple QComboBox
‘s items from its pull-down menu (with Shift or Alt+click to add/extract to-from current selection).
-
On a click QComboBox rolls down a pull-down menu.
-
But when the user makes a second mouse click (picking an item from pull-down menu)
ComboBox wouldn’t roll-back (or self-collapse) as it does by default. Instead it would stay open so the user is able to Shift+click more Combobox items to add or to extract them from selection. Finally when the user is happy with the selection the Enter
key is pressed to “confirm” the selection.
Here is a Photoshoped image showing the concept of “multi-selection” QComboBox I would like to achieve:
The code below creates QComboBox with almost every event exposed. But the only one I see “acting” is onMousePressEvent(). I can’t find the way to track down when the user selects the item from pull-down menu….
Edit:
Hour later I learned that QComboBox
can be set to multi selection via its .view().setSelectionMode(3)
.
Then the same .view()
could be used to query Combobox selected items:
selectedIndexes=self.view().selectionModel().selectedIndexes()
(where self
is a combo itself)
There is a way to select the Combo items using selectionModel.select(idx, QtGui.QItemSelectionModel.Select)
But so far I was not able to make it…..
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])
class Combo(QtGui.QComboBox):
def __init__(self, *args, **kwargs):
super(Combo, self).__init__()
self.addItems(['Item_1','Item_2','Item_3','Item_4','Item_5'])
self.view=self.view()
self.view.setSelectionMode(3)
self.activated.connect(self.clicked)
self.show()
def clicked(self, arg=None):
selectionModel=self.view.selectionModel()
selectedIndexes=selectionModel.selectedIndexes()
for idx in selectedIndexes:
selectionModel.select(idx, QtGui.QItemSelectionModel.Select)
print 'selecting idx: %s'%idx
self.showPopup()
tree=Combo()
sys.exit(app.exec_())
2
Answers
I ended up using the text colors to differentiate clicked (aka selected) items from others.
First click on ComboBox opens its pull-down menu. All following clicks are to select/deselect (highlighted red) items. Hit escape to close pull-down.
Other way, your can use just-like icon to check state. To easy than
QtGui.QStandardItem
. The methodQIcon QComboBox.itemIcon (self, int index)
and methodQComboBox.setItemIcon (self, int index, QIcon icon)
are available in classQtGui.QComboBox
;