How to set non-selectable default text on QComboBox?(如何在 QComboBox 上设置不可选择的默认文本?)
问题描述
使用填充有项目的常规 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 上设置不可选择的默认文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 QComboBox 上设置不可选择的默认文本?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
