combobox qt 设置不可更改,如何在QComboBox上设置不可选择的默认文本?

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(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:

(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!)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果您想在QComboBox控件中禁用某个选项,可以使用setItemData函数来存储一个自定义的角色(Qt::UserRole)来表示该选项是否可用。然后,您可以使用setItemDelegate函数设置一个自定义的委托来控制每个选项的绘制和交互。在该委托的paint和editorEvent函数中,您可以检查该选项是否可用,并相应地绘制或处理鼠标事件。下面是一个示例代码: ```python # 禁用第二个选项 combo_box.setItemData(1, False, Qt.UserRole) # 自定义委托 class ComboDelegate(QStyledItemDelegate): def paint(self, painter, option, index): if not index.data(Qt.UserRole): # 该项不可用,禁用绘制 option.state &= ~QStyle.State_Enabled super().paint(painter, option, index) def editorEvent(self, event, model, option, index): if not index.data(Qt.UserRole): # 该项不可用,禁用交互 return False return super().editorEvent(event, model, option, index) # 设置自定义委托 combo_box.setItemDelegate(ComboDelegate()) ``` 在上面的代码中,我们使用setItemData函数将第二个选项的自定义角色(Qt::UserRole)设置为False,表示该选项不可用。然后,我们创建了一个自定义委托ComboDelegate,并重写了其paint和editorEvent函数来检查每个选项是否可用,并相应地绘制和处理鼠标事件。最后,我们使用setItemDelegate函数将自定义委托设置QComboBox的委托。这样,当用户尝试选择第二个选项时,它将被禁用,并显示为灰色,无法交互。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值