Items disappears from combo box when I read them f

2019-02-28 12:18发布

问题:

I have QComboBox and I set QStandardItemModel because I need multi-select check-boxes in it. Problem is that when I read text value and check state of items in comboBox, they disappear from combo.

This is how I set model to comboBox:

areas = ["Area one", "Area two", "Area three", "Area four"]
model = QtGui.QStandardItemModel(4, 1)# 4 rows, 1 col
for i,area in enumerate(areas):
    item = QtGui.QStandardItem(area)
    item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    item.setData(QtCore.Qt.Unchecked, QtCore.Qt.CheckStateRole)
    model.setItem(i, 0, item)
self.ui.comboBox.setModel(model)

This is how I read data from comboBox:

modelColumn = self.ui.comboBox.model().takeColumn(0)
for item in modelColumn:
   print item.text(),"---", item.checkState()

Here is a screenshot before and after I read data from combo box:

...and result I get, as expected:

Area one --- 0
Area two --- 2
Area three --- 2
Area four --- 0

Also, is there simple way not to show "Area one" when comboBox is inactive (I want to see only arrow in right corner like on second picture) or to set other text to be shown, like "choose area"?

回答1:

Of course the combobox gets empty. You are actually removing the entire column 0 from your model:

from Qt doc:

takeColumn:

Removes the given column without deleting the column items, and returns a list of pointers to the removed items.

You may want to iterate your items thanks to this snippet (not tested):

rootItem = self.ui.comboBox.model().invisibleRootItem()
for rowNum in xrange(rootItem.rowCount()):
    item = rootItem.child(rowNum, 0)
    ...