I have a QComboBox that list all Windows' drive letters and let the user choose among them.
During the execution, we need to enable or disable some of the letters (without removing them).
Here is the basic code :
all_letters = ["{}:".format(chr(i)) for i in range(90, 64, -1)] # Z: -> A:
all_letters.insert(0, "")
cb_letter = QtGui.QComboBox()
for l in all_letters:
cb_letter.addItem(l)
cb_letter.setCurrentIndex(0)
I could find a kind of solution (which sounds really complicated) for just disabling an entry here but no way to enable it back.
What would be the best way to enable and disable any entry of a QComboBox?
By default, QComboBox
uses a QStandardItemModel
, so all of the convenience methods of QStandardItem
are available to you:
cb_letter.model().item(2).setEnabled(False)
Note: ekhumoro's answer above is probably all you need! Look no further, unless you have a reason to want to use a QAbstractItemModel instead of a QStandardItemModel.
Note 2: This is by no means a general purpose List Model. It was only intended to be used for a specific QComboBox in one of my applications. One should modify it for their intended purposes.
... anyway, I solved this problem by subclassing QAbstractListModel and then calling QComboBox.setModel(mylistmodel). My ListModel looks like this:
from PySide import QtCore
class ListModel(QtCore.QAbstractListModel):
"""
Class for list management with a QAbstractListModel.
Implements required virtual methods rowCount() and data().
Resizeable ListModels must implement insertRows(), removeRows().
If a nicely labeled header is desired, implement headerData().
"""
def __init__(self,input_list=[],parent=None):
super(ListModel,self).__init__(parent)
self.list_data = []
self.enabled = []
for thing in input_list:
self.append_item(thing)
def append_item(self,thing):
ins_row = self.rowCount()
self.beginInsertRows(QtCore.QModelIndex(),ins_row,ins_row+1)
self.list_data.append(thing)
self.enabled.append(True)
self.endInsertRows()
def remove_item(self,idx):
del_row = idx.row()
self.beginRemoveRows(QtCore.QModelIndex(),del_row,del_row)
self.list_data.pop(del_row)
self.enabled.pop(del_row)
self.endRemoveRows()
def set_disabled(self,row):
self.enabled[row] = False
def flags(self,idx):
if self.enabled[idx.row()]:
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
else:
return QtCore.Qt.NoItemFlags
def rowCount(self,parent=QtCore.QModelIndex()):
return len(self.list_data)
def data(self,idx,data_role):
return self.list_data[idx.row()]
def insertRows(self,row,count):
self.beginInsertRows(QtCore.QModelIndex(),row,row+count-1)
for j in range(row,row+count):
self.list_data.insert(j,None)
self.endInsertRows()
def removeRows(self, row, count, parent=QtCore.QModelIndex()):
self.beginRemoveRows(parent,row,row+count-1)
for j in range(row,row+count)[::-1]:
self.list_items.pop(j)
self.endRemoveRows()
def headerData(self,section,orientation,data_role):
return None