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 上设置不可选择的默认文本?
基础教程推荐
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04