Advertisement
Guest User

Untitled

a guest
Mar 4th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
QML 1.56 KB | None | 0 0
  1. import QtQuick 2.9
  2. import QtQuick.Window 2.2
  3. import QtQuick.Controls 2.2
  4.  
  5. Window {
  6.     id: root
  7.     visible: true
  8.     width: 640
  9.     height: 480
  10.     title: qsTr("Hello World")
  11.  
  12.     ListModel {
  13.         id: listModel
  14.         ListElement { text: "one"; value: 1 }
  15.         ListElement { text: "two"; value: 2 }
  16.         ListElement { text: "three"; value: 3 }
  17.         ListElement { text: "four"; value: 4 }
  18.     }
  19.  
  20.     property var arrayModel: [
  21.         { text: "one", value: 1 },
  22.         { text: "two", value: 2 },
  23.         { text: "three", value: 3 },
  24.         { text: "four", value: 4 }
  25.     ]
  26.  
  27.     property string myText: "three"
  28.     property var myValue: 3
  29.  
  30.     ComboBox {
  31.         id: comboBox
  32.         model: listModel
  33.         textRole: "text"
  34.         currentIndex: findValue(root.myValue)
  35.         onActivated: myText = currentText
  36.  
  37.         property string valueRole: "value"
  38.  
  39.         function findValue(value) {
  40.             print("findValue model count", model.length || model.count)
  41.             if (!valueRole)
  42.                 return -1;
  43.  
  44.             if (Array.isArray(model)) {
  45.                 return model.findIndex(data => data && typeof data === "object" && data.hasOwnProperty(valueRole) && data[valueRole] === value);
  46.             } else {
  47.                 for (var i = 0; i < model.count; ++i) {
  48.                     if (model.get(i)[valueRole] === value)
  49.                         return i;
  50.                 }
  51.                 return -1;
  52.             }
  53.         }
  54.     }
  55.  
  56.     Text {
  57.         x: 200
  58.         text: comboBox.currentText
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement