問題描述
使用填充有項目的常規(guī) QComboBox
,如果 currentIndex
設(shè)置為 -1
,則小部件為空.在組合框中顯示初始描述性文本(例如--選擇國家/地區(qū)--"、--選擇主題--"等)會非常有用,該文本未顯示在下拉列表中.
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.
我在文檔中找不到任何內(nèi)容,也沒有找到任何以前的問題的答案.
I couldn't find anything in the documentation, nor any previous questions with answers.
推薦答案
Combo Box API 中似乎沒有預(yù)料到這種情況.但是由于底層模型的靈活性,您似乎應(yīng)該能夠?qū)⒛?--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);
根據(jù)您想要的精確行為,您可能希望改用 setEnabled
.或者我個人更喜歡它,如果它只是我可以將其設(shè)置回的不同顏色的項目:
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++)
(我不喜歡當(dāng)我點擊某個東西然后被困在我無法回到原來的地方時,即使它是一個沒有選擇的狀態(tài)!)
這篇關(guān)于如何在 QComboBox 上設(shè)置不可選擇的默認(rèn)文本?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!