I'm trying to make a list of buttons, where the user can select one of the options. I can't seem to display the text from the listmodel, but I can't figure out why. It seems like even the button is not correctly placed. Does anyone have ideas as to how to fix this? Thanks!
import QtQuick 2.15
import QtQuick.Window 2.2
import QtQuick.Controls 2.15
Window {
id: window
visible: true
height: 400
width: 400
Rectangle {
id: rect
width: 400; height: 400
ListView {
id: listview
anchors.fill: parent
model: timeList
delegate: Item {
anchors.top: parent.top
height: 30
Button {
anchors.top: parent.top
anchors.left: parent.left
id: textButton
text: text
width: parent.width
height: 30
flat: true
onClicked: {
console.log(value)
}
}
Rectangle {
height: (index === timeList.count - 1 ? 0 : 1)
color: '#E1E6E9'
width: 400
anchors {
left: textButton.left
top: textButton.bottom
}
}
}
ListModel {
id: timeList
ListElement { text: "15 minutes"; value: 15 }
ListElement { text: "1 hour"; value: 60 }
ListElement { text: "3 hours"; value: 180 }
ListElement { text: "6 hours"; value: 360 }
ListElement { text: "12 hours"; value: 720 }
}
}
}
}
CodePudding user response:
There are several issues here:
- don't name
ListElement
properties using keywords,text: text
looks confusing. - don't wrap everything with
Rectangle
/Item
with no need, useLayout
instead if needed - never use anchors for delegates
- pay attention that all containers have a size, the delegate's
Item
has no with for example (or probably 0)
actually, that should work:
import QtQuick
import QtQuick.Window
import QtQuick.Controls
Window {
id: window
visible: true
height: 400
width: 400
ListView {
anchors.fill: parent
model: timeList
delegate: Button {
id: textButton
text: name
width: parent.width
height: 30
flat: true
onClicked: {
console.log(value)
}
}
ListModel {
id: timeList
ListElement { name: "15 minutes"; value: 15 }
ListElement { name: "1 hour"; value: 60 }
ListElement { name: "3 hours"; value: 180 }
ListElement { name: "6 hours"; value: 360 }
ListElement { name: "12 hours"; value: 720 }
}
}
}