如何在 QComboBox 上设置不可选择的默认文本?

2023-01-22C/C++开发问题
6

本文介绍了如何在 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 上设置不可选择的默认文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6