使用填充有项目的常规 QComboBox
,如果 currentIndex
设置为 -1
,则小部件为空.在组合框中显示初始描述性文本(例如--选择国家/地区--"、--选择主题--"等)会非常有用,该文本未显示在下拉列表中.
Using a regular QComboBox
populated with items, if currentIndex
is set to -1
, the widget is empty. It would be very useful to instead have an initial descriptive text visible in the combo box(e.g. "--Select Country--", "--Choose Topic--", etc.) which is not shown in the dropdown list.
我在文档中找不到任何内容,也没有找到任何以前的问题的答案.
I couldn't find anything in the documentation, nor any previous questions with answers.
Combo Box API 中似乎没有预料到这种情况.但是由于底层模型的灵活性,您似乎应该能够将您的 --Select Country-- 添加为第一个合法"项目,然后使其不被用户选择:
It doesn't appear that case was anticipated in the Combo Box API. But with the underlying model flexibility it seems you should be able to add your --Select Country-- as a first "legitimate" item, and then keep it from being user selectable:
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
.或者我个人更喜欢它,如果它只是我可以将其设置回的不同颜色的项目:
Depending on what precise behavior you want, you might want to use setEnabled
instead. Or I'd personally prefer it if it was just a different color item that I could set it back to:
Qt,如何更改 QComboBox 的一项的文本颜色?(C++)
(我不喜欢当我点击某个东西然后被困在我无法回到原来的地方时,即使它是一个没有选择的状态!)
这篇关于如何在 QComboBox 上设置不可选择的默认文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!