背景:
项目需要用到Combobox,而我在后台的数据都是json字符串,我的习惯是尽量使用弱类型,以为传输方便。及时需要解析或者赋值,再使用JSON的parse和stringify函数转换,当然这个转换要考虑到安全性。
所以但凡是TableView或者Combobox这类的model,我都是直接使用json。
Combobox的关键数据无非就是index,value,text。使用时要能自由转换,亦即通过任何一个值能准确获得其它任意一个。特此记录下来方便查阅。
所以就有了下面的demo。
demo:
import QtQuick
import QtQuick.Controls
Item {
Row {
ComboBox {
id: cb
valueRole: "value"
textRole: "text"
model: [
{ value: "v0", text: "t0" },
{ value: "v1", text: "t1" },
{ value: "v2", text: "t2" }
]
onActivated: {
print("GetIndexByText: text=" + currentText + ", index=" + find(currentText));
print("GetIndexByValue: value=" + currentValue + ", index=" + indexOfValue(currentValue));
print("GetValueByIndex: index=" + currentIndex + ", value=" + valueAt(currentIndex));
print("GetValueByText: text=" + currentText + ", value=" + valueAt(find(currentText)));
print("GetTextByIndex: index=" + currentIndex + ", text=" + textAt(currentIndex));
print("GetTextByValue: value=" + currentValue + ", text=" + textAt(indexOfValue(currentValue)));
}
}
Button {
text: "press"
onClicked: {
cb.currentIndex = -1;
}
}
}
}
实际项目中,它的model我是用js动态加载的。
在onActivated槽函数中,特意写了转换代码。从输出字符中,应该见名知意了。
无非就是几个函数的应用:find,indexOfValue,valueAt,textAt。
如果让Combobox哪个也不选,就让index=-1。
效果:
结束:
本文完。