如果使用填充了项目的常规 QComboBox
,并将 currentIndex
设置为 -1
,则小部件为空。相反地,在组合框中显示一个初始描述性文本(例如“--选择国家--”,“--选择主题--”等),但不在下拉列表中显示,将非常有用。
我在文档和以往的问题与答案中都没有找到任何内容。
似乎组合框API没有考虑到这种情况,但是由于底层模型的灵活性,你应该能够将--选择国家--作为第一个“合法”项目添加,并防止用户选择它:
QStandardItemModel* model =
qobject_cast<QStandardItemModel*>(comboBox->model());
QModelIndex firstIndex = model->index(0, comboBox->modelColumn(),
comboBox->rootModelIndex());
QStandardItem* firstItem = model->itemFromIndex(firstIndex);
firstItem->setSelectable(false);
根据您想要的具体行为,您可能需要使用setEnabled
。或者我个人更喜欢它只是一个不同颜色的项目,我可以将其设置回去:
Qt,如何更改QComboBox的一个项目的文本颜色?(C ++)
(我不喜欢点击某些东西,然后被困在无法返回到之前状态的地方,即使它是未选择任何内容的状态!)
我在这里提供一个基于PyQt5的解决方案。创建一个代理模型并将所有行向下移动一行,并在第0行返回默认值。
class NullRowProxyModel(QAbstractProxyModel):
"""Creates an empty row at the top for null selections on combo boxes
"""
def __init__(self, src, text='---', parent=None):
super(NullRowProxyModel, self).__init__(parent)
self._text = text
self.setSourceModel(src)
def mapToSource(self, proxyIndex: QModelIndex) -> QModelIndex:
if self.sourceModel():
return self.sourceModel().index(proxyIndex.row()-1, proxyIndex.column())
else:
return QModelIndex()
def mapFromSource(self, sourceIndex: QModelIndex) -> QModelIndex:
return self.index(sourceIndex.row()+1, sourceIndex.column())
def data(self, proxyIndex: QModelIndex, role=Qt.DisplayRole) -> typing.Any:
if proxyIndex.row() == 0 and role == Qt.DisplayRole:
return self._text
elif proxyIndex.row() == 0 and role == Qt.EditRole:
return None
else:
return super(NullRowProxyModel, self).data(proxyIndex, role)
def index(self, row: int, column: int, parent: QModelIndex = ...) -> QModelIndex:
return self.createIndex(row, column)
def parent(self, child: QModelIndex) -> QModelIndex:
return QModelIndex()
def rowCount(self, parent: QModelIndex = ...) -> int:
return self.sourceModel().rowCount()+1 if self.sourceModel() else 0
def columnCount(self, parent: QModelIndex = ...) -> int:
return self.sourceModel().columnCount() if self.sourceModel() else 0
def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...) -> typing.Any:
if not self.sourceModel():
return None
if orientation == Qt.Vertical:
return self.sourceModel().headerData(section-1, orientation, role)
else:
return self.sourceModel().headerData(section, orientation, role)
setPlaceholderText
,如此处所答复的:https://dev59.com/VWsz5IYBdhLWcg3w0rZC#63937462 - Luc Touraille