如何在QComboBox上设置不可选择的默认文本? [英] How to set non-selectable default text on QComboBox?

查看:3655
本文介绍了如何在QComboBox上设置不可选择的默认文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用填充了项目的常规 QComboBox ,如果 currentIndex 设置为 -1 ,窗口小部件为空。在下拉列表中没有显示的组合框中显示初始描述性文本(例如--Select Country--, - 选择主题 - 等)将非常有用。 / p>

我在文档中找不到任何内容,也没有任何以前有问题的答案。

解决方案

在Combo Box 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 ++)



(我不喜欢它,当我点击的东西,然后被困在哪里,我不能回到哪里我是,即使它是一个没有选择的状态!)


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.

解决方案

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);

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, How do I change the text color of one item of a QComboBox? (C++)

(I don't like it when I click on something and then get trapped to where I can't get back where I was, even if it's a nothing-selected-yet-state!)

这篇关于如何在QComboBox上设置不可选择的默认文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆