from
PyQt5.QtWidgets
import
QApplication, QComboBox, QMainWindow
from
PyQt5.QtWidgets
import
QWidget, QVBoxLayout
from
PyQt5.QtGui
import
QStandardItemModel
from
PyQt5.QtCore
import
Qt
import
sys
class
CheckableComboBox(QComboBox):
def
__init__(
self
):
super
(CheckableComboBox,
self
).__init__()
self
.view().pressed.connect(
self
.handle_item_pressed)
self
.setModel(QStandardItemModel(
self
))
def
handle_item_pressed(
self
, index):
item
=
self
.model().itemFromIndex(index)
if
item.checkState()
=
=
Qt.Checked:
item.setCheckState(Qt.Unchecked)
else
:
item.setCheckState(Qt.Checked)
self
.check_items()
def
item_checked(
self
, index):
item
=
self
.model().item(index,
0
)
return
item.checkState()
=
=
Qt.Checked
def
check_items(
self
):
checkedItems
=
[]
for
i
in
range
(
self
.count()):
if
self
.item_checked(i):
checkedItems.append(i)
self
.update_labels(checkedItems)
def
update_labels(
self
, item_list):
n
=
''
count
=
0
for
i
in
item_list:
if
count
=
=
0
:
n
+
=
' % s'
%
i
else
:
n
+
=
', % s'
%
i
count
+
=
1
for
i
in
range
(
self
.count()):
text_label
=
self
.model().item(i,
0
).text()
if
text_label.find(
'-'
) >
=
0
:
text_label
=
text_label.split(
'-'
)[
0
]
item_new_text_label
=
text_label
+
' - selected index: '
+
n
self
.setItemText(i, item_new_text_label)
sys.stdout.flush()
class
Window(QMainWindow):
def
__init__(
self
):
super
(QMainWindow,
self
).__init__()
myQWidget
=
QWidget()
myBoxLayout
=
QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self
.setCentralWidget(myQWidget)
self
.ComboBox
=
CheckableComboBox()
for
i
in
range
(
3
):
self
.ComboBox.addItem("Combobox Item "
+
str
(i))
item
=
self
.ComboBox.model().item(i,
0
)
item.setCheckState(Qt.Unchecked)
myBoxLayout.addWidget(
self
.ComboBox)
if
__name__
=
=
'__main__'
:
app
=
QApplication(sys.argv)
window
=
Window()
window.show()
window.resize(
480
,
320
)
sys.exit(app.exec_())