I am trying to display a list of values with a slider in QML. Those values have an irregular step size, i.e [10, 20, 30, 50, 75, 100]. How would i go about doing this with a QML slider (must be a slider due to design constraints)? Slider does not have a model property sadly, so I cant do it that way. Of course i could create my own custom slider from scratch, but if there is an easier way, why reinvent the wheel?
CodePudding user response:
Solution
Setup the range and the step of the slider, e.g.:
from: 0; to: 5; stepSize: 1
Use a JS function to convert the slider value to whatever you need, e.g.:
function hash(x) {
var table = [10, 20, 30, 50, 75, 100];
return table[x];
}
Note: For complex conversions consider calling a method of a class from the C backend.
Example
Here is a simple example I have written for you to demonstrate the proposed solution:
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.12
ApplicationWindow {
width: 640; height: 480
visible: true
title: qsTr("QML Slider Values")
function hash(x) {
var table = [10, 20, 30, 50, 75, 100];
return table[x];
}
ColumnLayout {
anchors.centerIn: parent
Slider {
id: slider
from: 0; to: 5; stepSize: 1
}
Text {
text: hash(slider.value)
Layout.alignment: Layout.Center
}
}
}
EDIT:
Inspired by @fallerd, I rewrote the ColumnLayout-part a little bit moderner:
ColumnLayout {
anchors.centerIn: parent
Slider {
id: slider
property var hashTable: [10, 20, 30, 50, 75, 100];
readonly property int hashedValue: (() => hashTable[value])();
from: 0; to: hashTable.length - 1; stepSize: 1
}
Text {
text: slider.hashedValue
Layout.alignment: Layout.Center
}
}
