In ListView, how can you set the currentIndex or currentItem to a dynamically created element? - qt

I got a listview with a c++ listmodel and a rectangle with a mousarea as delegate.
Internally in my code, my listmodel gets data appended, and I do
beginResetModel();
list.append(element);
endResetModel();
My model updates and the element appears just fine, but I am not able to set the currentIndex to the newly created item.
I am trying to use Component.onCompleted inside the delegate like this
Component.onCompleted: {
ListView.currentIndex = index;
console.log("Show List: ", ListView.currentIndex, index);
}
But the index in the log output says the currentIndex doesn't change after I set it to my models index.
I do the same inside my mousearea, in onClicked, and there it works fine.
How can I make my newly created listview element the currentItem/currentIndex?
I am using this currentIndex to change the color of the created element (this is inside my rectangle delegate)
color: ListView.currentIndex == index ? "lightred" : "darkred"
Are there better ways of going about what I am trying to do possibly?
Full code example below:
ListView {
id: listView
focus: true
clip: true
model: listModel
delegate: Rectangle {
id: listDelegate
color: listView.currentIndex == index ? "green" : "red"
height: 20
width: 100
radius: 2
Component.onCompleted: {
listView.currentIndex = index
console.log("Show List: ", listView.currentIndex, index)
}
MouseArea {
anchors.fill: parent
onClicked: {
listView.currentIndex = index
console.log("onClicked: ", listView.currentIndex, index)
}
}
}
}

You can just check for when the count changes, like this:
ListView {
...
onCountChanged: {
listView.currentIndex = listView.count - 1;
}
}

Related

Set text in a label in a listview from a textfield outside listview in qml

I have the following ListView in QML:
ListView{
id:daylistView
width:parent.width
height:parent.height - eventDayLabel.height
boundsBehavior:Flickable.StopAtBounds
highlightRangeMode: ListView.StrictlyEnforceRange
orientation: Qt.Vertical
anchors.top:eventDateRow.bottom
clip:true
focus:true
model: 24
currentIndex : calendarMonth.selectedDate.getDate() === new Date().getDate()
&& calendarMonth.selectedDate.getMonth() === new Date().getMonth()?getHour():12
interactive: true
delegate: Item{
id:hourItem
property var hourTime:hourweeklistviewLabel
width: daylistView.width
height: 60
MouseArea{
anchors.fill:parent
onClicked:{
windowLoader.active =true
daylistView.currentIndex=index
}
}
Rectangle {
z:4
id:hourdaylistviewindexLine
y:getdayMinute()
width:hourItem.width
height:2
border.color: calendarMonth.selectedDate.getDate()===new Date().getDate()
&& getHour() === hourweeklistviewLabel.text
&& calendarMonth.selectedDate.getMonth() === new Date().getMonth()
?"red" : "transparent"
border.width:1
}
Rectangle {
z:4
id:hourline
anchors.verticalCenter: daylistView
width:daylistView.width
height:2
border.color: "lightgray"
border.width:1
}
Label{
z:4
id:hourweeklistviewLabel
anchors.verticalCenter: parent
text:['00','01','02','03',
'04','05','06','07','08','09','10','11','12','13',
'14','15','16','17','18','19','20','21','22','23'][index]
color: getHour() === hourweeklistviewLabel.text
&& calendarMonth.selectedDate.getDate() === new Date().getDate()
&& calendarMonth.selectedDate.getDay() === new Date().getDay()
? systemPalette.highlight : "lightgray"
}
Label{
z:4
id:notesLabel
anchors.left:hourweeklistviewLabel.right
//text:" "
}
}
}
}
It is a day calendar app, where the ListView delegates hourly time.The delegate includes a mouse area , two rectangles and two labels.The one Label is read only.In the other Label, I want to set text from a TextInput, outside ListView, from another window.Far more the objective is to display the label in specific hour time, meaning in a specific row of ListView.Until now I managed to get the currentItem hour, but I can't set the text in the Label in ListView in currentIndex, although I tried a lot of suggested methods I found in the web.If i find a way to set the text in currenItem Label then I could choose to set it, in any other index in Listview.
As #SoheilArmin comment, the solution lies on binding Label text to a property.In the ListView code:
delegate: Item{
id:hourItem
property var hourTime:hourweeklistviewLabel
**property var notetaking: notesLabel**
width: daylistView.width
height: 60
set property var notetaking: notesLabel .
Then in the TextField:
TextField {
id:title
x:50
y:20
placeholderText :'Enter Note'
text:daylistView.currentItem.notetaking.text
}
set text:daylistView.currentItem.notetaking.text
thus, we have a bidirectional binding .
Also define a button so can set the text to the label:
Button {
id: button
text: qsTr("Add Note")
anchors.centerIn:parent
onClicked: {
if (title.text !==""){daylistView.currentItem.notetaking.text= title.text}
else{}
}
}

How to anchor a dialog to a button in listview qt qml

I have a row for a listview delegate with buttons on it. On click of a button, i need a dialog to open just below that button. I tried mapToItem property and partially succeeded but this listview is scrollable and on scrolling the dialog stays in its initial position. Unsure of how to get it working. Also, new to posting questions. Kindly ignore if I am being vague and help me out.
The dialog i want to open is placed outside of this delegate. I have provided a short outline of my code.
Listview{
delegate: Row{
Button1{
}
Button2{
id: button2Id
onCheckedChanged{
var coords = button2Id.mapToItem(null,0,0)
dialogId.x = coords.x
dialogId.y= coords.y
dialogId.visible = true
}
}
}
}
//dialog rect outside of my listview
Rectangle{
id: dialogId
}
You could add the dialog to the highlight item of the list. I have modified your example a little so that I could test it. I encapsulated your Rectangle in an Item because ListView controls the size and position of the root object of the highlight. The Rectangle then just has to be anchored to the bottom of that Item.
ListView {
id: lv
width: 200
height: parent.height
model: 50
spacing: 1
currentIndex: -1
delegate: Row {
spacing: 1
height: 40
Button {
text: index
}
Button {
id: button2Id
text: ">"
onClicked: {
lv.currentIndex = index;
}
}
}
highlight: Item { // ListView controls the size/pos of this Item
z: 1
Rectangle {
id: dialogId
anchors.top: parent.bottom // Anchor to bottom of parent
width: 200
height: 100
color: "red"
}
}
}
UPDATE:
Here is a way to keep the dialog directly under the button without calculating margins. I put it in a Loader so that each item in the list doesn't always carry the whole dialog around with it. It might make a performance difference.
The ugly part of this solution is the z-ordering. Each item in the list is drawn after the one that comes sequentially before it. (I'm not actually sure if that's even guaranteed.) That means the dialog gets drawn underneath any item that comes after it in the list. I was able to get around that by changing the z value of each item in the list to be less than the item before it.
ListView {
id: lv
width: 200
height: parent.height
model: 50
spacing: 1
currentIndex: -1
delegate: Row {
z: lv.count - index // <<- z-value fix
spacing: 1
height: 40
Button {
text: index
}
Button {
id: button2Id
text: ">"
onClicked: {
lv.currentIndex = index;
}
Loader {
anchors.top: parent.bottom
asynchronous: true
sourceComponent: (index === lv.currentIndex) ? dialogComp : null
}
}
}
}
Component {
id: dialogComp
Rectangle {
id: dialogId
width: 200
height: 100
color: "red"
}
}

Warnings in QML: Delegate in separate file and access on model item properties

The following code works and shows my items correctly, but I get the warning
qrc:/TableDelegate.qml:24: ReferenceError: name is not defined
I think it is because the ListView tries to access the model when it is empty and can not reference the item properties. I assume I am not doing to it correctly but I do not know how to do it better.
So my question is: how to get rid of the warning by doing it the right way?
TableDelegate.qml:
import QtQuick 2.0
import QtQuick.Layouts 1.1
Item {
property color bgcolor: 'transparent'
property alias box: rowBox
height: 40
width: parent.width
Rectangle {
id: rowBox
anchors.fill: parent
color: bgcolor
RowLayout {
anchors.fill: parent
Rectangle {
id: tableNameColumn
color: 'transparent'
Layout.fillHeight: true
Layout.fillWidth: true
Text {
anchors.centerIn: parent
color: textcolor
text: name // <--- here is `name`
}
}
// More Columns ...
}
}
MouseArea {
anchors.fill: parent
onClicked: {
view.currentIndex = index
}
}
}
And I use it like this
TableView.qml:
// ...
ListModel {
id: model
}
ListView {
id: view
model: model
anchors.fill: parent
highlight: delegate_highlighted
highlightFollowsCurrentItem: true
delegate: delegate
}
Component {
id: delegate
TableDelegate {
bgcolor: 'transparent';
}
}
Component {
id: delegate_highlighted
TableDelegate {
bgcolor: 'lightsteelblue'
box.border.color: 'black'
box.radius: 3
}
}
// ...
You use a TableDelegate for the highlight. That is wrong.
The ListView creates 1 instance of the highlight item, that will be drawn as a background for the currently selected item, It may also move between items as transition when the current item changes. It should only be a rectangle or whatever you want to use.
In your example, the highlight item is a full delegate, that wants to access model data, which it cannot.

QML/QtQuick Binding delegate's property with ListView's currentIndex

Inside the delegate, I bind Image's source property to ListView's currentIndex which determines which image to load. This works great:
ListView {
id: answerListView
model: 5
currentIndex: -1
delegate: answerDelegate
}
Component {
id: answerDelegate
Item {
width: 100
height: 100
Image {
source: answerListView.currentIndex === index
? "selected.png" : "not_selected.png"
}
MouseArea {
anchors.fill: parent
onClicked: {
answerListView.currentIndex = index
}
}
Component.onCompleted: {
answerListView.currentIndex = 1; // doesn't work!!
}
}
}
Since currentIndex: -1, it will always show not_selected.png. To show selected.png, I change currentIndex in Component.onLoaded inside delegate.
I was expecting image to load selected.png since currentIndex was updated.
What is the correct way and what am I misunderstanding here?
Ok, new guess:
You want to have the posibility to select multiple Items. As currentIndex only stores one value, which is the value you assigned it last, you can use it to mark only one Item.
Therefore you need to find another way to store your selection. You might for example have a property in the delegate: property bool selected: false which you set to true upon selection.
The problem with this solution is, that it only works if all Items are instantiated at all times. As soon as one Item will be destroyed again, the information will be lost, and uppon the next creation, the selection/unselection is undone.
The better way would be to introduce a role in your model, that stores the selection outside of the non-persistant delegates for you:
ListView {
id: answerListView
model: lm
delegate: answerDelegate
width: 100
height: 220
}
ListModel {
id: lm
ListElement { selected: false }
ListElement { selected: false }
ListElement { selected: false }
ListElement { selected: false }
ListElement { selected: false }
}
Component {
id: answerDelegate
Item {
width: 100
height: 100
Image {
anchors.fill: parent
source: model.selected ? "selected.png" : "notselected.png"
}
Text {
text: (model.selected ? 'selected ' : 'notselected ')
}
Component.onCompleted: {
model.selected = true // doesn't work!!
}
MouseArea {
anchors.fill: parent
onClicked: {
model.selected = !model.selected
}
}
}
}
Another option would probably be a ItemSelectionModel, but I don't know atm, how it works.
Otherwise your example works as expected:
The Item with index 1 is shown, and displays the Image selected.png. All other Items are not shown (for the ListView is to small) but if the would be shown, they would show notselected.png for the answerListView.currentIndex is not equal to their index.

Unable to access QML variable / id globally

I have QtQuick 1.0
I use the following code:
Rectangle {
Component {
id: appDelegate
MouseArea{
id:myMouseArea
hoverEnabled: true
onClicked:{
onClicked: load.source = page;
}
}
Loader {
id: load
}
}
GridView {
id: view
// I am unable to access myMouseArea here.
highlight: myMouseArea.containsMouse ? appHighlight : !appHighlight
delegate: appDelegate
}
}
It gives me the following error:
ReferenceError: Can't find variable: myMouseArea
/usr/lib/i386-linux-gnu/qt4/bin/qmlviewer exited with code 0
I don't know if the details I provided are sufficient, please let me know if theres anything else I am missing.
I am using this code as an example:
http://docs.knobbits.org/qt4/declarative-modelviews-gridview-qml-gridview-example-gridview-example-qml.html
You cannot access myMouseArea because it's created inside delegate context. You cannot access delegate other then currentItem. But you can freely access view inside the context of delegate, to set currentIndex to attached property index.
This is a corrected code:
Rectangle {
width: 360
height: 360
Component { // It must be a component, if we want use it as delegate
id: appDelegate
// its not possible to have more than one element inside component
Rectangle
{
// need to set size of item, anchors wont work here
// could use view.cellWidth and view.cellHeight to keep it DRY
width: 96
height: 66
color: "green" // color only to see the place of MouseArea
MouseArea {
id:myMouseArea
anchors.fill: parent // this setup the size to whole rectangle
// it this item have the size 0,0 it will simple do not work
hoverEnabled: true
onEntered: {
// we know the mouse is inside this region
// setting this value will show the highlight rectangle
view.currentIndex = index;
}
onClicked:{
onClicked: load.source = page;
}
}
Loader {
// this is not needed but it's wise to not keep zero size
anchors.fill: parent
id: load
}
}
}
GridView {
id: view
// the size of GridView must be set,
// as otherwise no delegate will not show
anchors.fill: parent
anchors.margins: 5
cellWidth: 100
cellHeight: 70
// Rectangle will act as a border.
// Size and position is set by GridView
// to the size and position of currentItem.
// This is no a item, this makes a Component
// as highlight property needs one.
// You can create a Component like appDelegate.
highlight : Rectangle {
border.width: 2
border.color: "blue"
}
// some ListModel to setup the page variable inside delegate context
model: ListModel {
ListElement { page: "test1.qml"; }
ListElement { page: "test2.qml"; }
ListElement { page: "test3.qml"; }
}
delegate: appDelegate
}
}

Resources