How to set non-selectable default text on QComboBox?

后端 未结 3 1370
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 09:54

Using a regular QComboBox populated with items, if currentIndex is set to -1, the widget is empty. It would be very useful to instead

3条回答
  •  太阳男子
    2020-12-06 10:13

    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:

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

提交回复
热议问题