Important: Please read the Qt Code of Conduct -

Qml ComboBox and current model item

  • Hi everyone.
    I have a question about Quick Controls 2 ComboBox (2.12), I have a key-value model inherited from QAbstractItemModel, basically it has 2 roles: one I use to display some printable data, other is the key. How can I fetch the key of the selected combobox item? I know that Controls 2.14 added valueRole property to the ComboBox control, but I can't upgrade Qt, at least for now.

  • currentIndex

    maybe i misunderstand but can't you just use the index. Because it's model driven, and the one and the same model...

  • @6thC I mean I have key value model such as:
    "key-1" - "value-1"
    "key-2" - "value 2";
    I use value field as a "textRole" of the ComboBox, but if the currentIndex is changed I need to determine an Id of the selected item to proceed.

  • Qt Champions 2018

    assuming your model as an invokable get method returning a map of all the role values:

    property string valueRole
    readonly property var currentValue: valueRole && model ? model.get(currentIndex)[valueRole] : undefined

  • @GrecKo In case if I will manually extend my model's public interface in that way I will lost the possibility to chain models (e.g. set qsortfilterproxymodel in front of my model).
    I decided to expose my custom Roles to the qml part and fetch the data via QAbstractItemModel::data method by hand.

    function getModelKeyByRow(model, row) {
    	let modelIndex = model.index(row, 0);
    	return, QtExtras.KeyValueModel.KeyRole);

    I thought maybe there is some more convenient way :) But I'm absolutely fine with it right now. Someday I will upgrade Qt to 5.14 and the problem will disappear.
    Thank you folks!

Log in to reply