Qml: How to set a property to all GridView items - qt

I am trying to make a change to all items of a GridView.
I have tried to iterate through either the model or the grid, I looked at similar examples on the web, but everything I try ends with Cannot read property 'buttonText' of undefined.
It seems to me that the problem is that the interpreter can't figure out that the item from the grid or model is a Button. But I don't know how to cast it.
If I change the log to only display the item, not any property, (see code snippet), it seems that it knows it is an item... see my experiments below.
The only thing I can make work is set a property (or call a signal, or a function) from the delegate. But that only affects one grid item, not all.
How can I set a property on every item of the grid ? Alternatively, how can I send a signal, or call a function, on every item?
My experiments are in function changeEverythingFunction()
file: Button.qml
Item
{
id: itemButton
signal changeEverything
property int buttonIndex
property string buttonText
...
}
file: Model.qml
Item
{
id: modelItem
ListModel
{
id: listModel
}
property int buttonCount: listModel.count
function changeEverythingFunction()
{
// for (var i = 0; i < buttonCount; i++)
// listModel.setProperty(i, buttonText, "abc")
for(var childIndex in gridItems.contentItem.children)
{
console.log(listModel.get(childIndex).buttonText) // Cannot read property 'buttonText' of undefined
console.log(gridItems.contentItem.children[childIndex].buttonText) // Cannot read property 'buttonText' of undefined
console.log(gridItems.contentItem.children[childIndex]["buttonText"]) // undefined (I saw this in a SO example)
var item = gridItems.contentItem.children[childIndex]
console.log(item) // qml: QQuickItem(0xe496370)
}
}
MouseArea
{
....
Rectangle
{
...
GridView
{
id: gridItems
anchors.fill: parent
clip: true
model: listModel
delegate: Item
{
id: buttonDelegate
Button
{
buttonIndex: gridId
buttonText: itemText
onChangeEverything:
{
changeEverythingFunction();
}
}
}
}
}
}
}

Your approach is in the opposite direction: Your approach is to obtain the item of the view and modify it, but the approach that Qt points out is that the view reflects the information of the model and modifies it when necessary.
The following is a simple example where every time you press on the button with "change me" text increasing the number it shows, but if you press the button with "change all" text it will change all the numbers. As it is observed everything is done through the model, not through the view that are only used to display information or receive user interaction.
import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.14
Window {
visible: true
width: 640
height: 480
ListModel{
id: listmodel
}
function changeAll(){
for(var i=0; i< listmodel.count; ++i){
listmodel.setProperty(i, "number", listmodel.get(i).number + 1)
}
}
GridView{
id: grid
anchors.fill: parent
clip: true
model: listmodel
cellHeight: 120
cellWidth: 120
delegate: Item {
width: grid.cellWidth; height: grid.cellHeight
Column {
anchors.fill: parent
Text { text: model.number; anchors.horizontalCenter: parent.horizontalCenter }
Button{text: "change me"; onClicked: model.number +=1}
Button{text: "change all"; onClicked: changeAll()}
}
}
}
Component.onCompleted: {
for(var i=0; i < 10; ++i){
listmodel.append({"number": 0});
}
}
}

Related

How to correctly bind a property from model to property in hand-made Item in delegate?

I want to make an editing delegate for a ListView for an arbitrary model.
In delegate I want to use my own NeatInput inherited from TextInput. NeatInput declares own property realValue, binds text to realValue, and, to make it two-way, upon textChanged signal changes realValue. That works as expected:
/*NeatInput.qml*/
import QtQuick 2.0
TextInput {
width: 50
property real realValue: 0.0
text: realValue * 2
onTextChanged: {
realValue = Number.fromLocaleString(locale, text) / 2
}
}
Now, it is used simply as a delegate in ListView, with binding realValue on someValue from model, and, for edit purpose, writing to someValue upon realValueChanged:
/*main.qml*/
import QtQuick 2.12
import QtQuick.Controls 2.12
ApplicationWindow {
width: 500
height: 500
visible: true
ListView {
id: view
model: ListModel {
ListElement {
someValue: 50
}
}
anchors.fill: parent
delegate: Row {
NeatInput {
realValue: someValue
onRealValueChanged: someValue = realValue
}
SpinBox {
value: someValue
onValueChanged: someValue = value
}
Text {
width: 50
text: someValue
}
}
}
}
Text for simple reading, SpinBox for read/write with standard Item.
But this doesn't work as I expect:
Editing from SpinBox updates Text only;
Editing from NeatInput updates both SpinBox and Text.
So, binding on someValue for NeatInput is broken someway, but writes work.
If I remove signal binding onTextChanged from NeatInput.qml, then:
Editing from SpinBox updates both Text and NeatInput;
Editing from NeatInput updates nothing.
What should I do to make updates work from both editors to all readers?
The general rule of thumb is always: assignments break bindings. Whenever you do this:
onTextChanged: {
realValue = Number.fromLocaleString(locale, text) / 2
}
it breaks the binding that you created here:
realValue: someValue
So the first time text changes, realValue will stop listening for updates to someValue.
Two-way bindings are always tricky because they become circular. I played with your code for a minute and got it working by doing this:
ListView {
id: view
model: ListModel {
ListElement {
someValue: 50
}
}
anchors.fill: parent
delegate: Row {
NeatInput {
realValue: someValue
onRealValueChanged: someValue = realValue
property real someValueCopy: someValue
onSomeValueCopyChanged:
{
realValue = someValueCopy;
}
}
SpinBox {
value: someValue
onValueChanged: someValue = value
}
Text {
width: 50
text: someValue
}
}
}

How can I get property in gridview which is Repeater's child

how can i get gridView.itemAtIndex(index).color?
what is i have tried:
contentrepeater.itemAt(5).gridView.model.color;
contentrepeater.itemAt(5).gridView.itemAtIndex(5).color;
But it doesn't work
Rectangle {
anchors.top: bar.bottom
Layout.fillHeight: true
Layout.fillWidth: true
Repeater {
id: contentrepeater
model: 11
Rectangle {
anchors.fill: parent
color: 'red'
visible: false
GridView {
id: gridView
anchors.fill: parent
anchors.topMargin: 10
anchors.leftMargin: 10
cellWidth: 150
cellHeight: 170
clip: true
model: 11
delegate: Rectangle{
height: 160
width: 140
color: '#333333'
}
}
}
}
}
Ultimately you probably don't want to do it that way. It will be hackish and error-prone. For example GridView only provides item access based on position coordinates, not indexes. So you'd need to dive into its children which are going to be created dynamically... it's possible but very messy and not really supported API.
You are better off defining your item models first, then using the GridView (or whatever) to display them. That way you can manipulate objects in the models and changes will be reflected in the view (instead of the other way around like you're trying now).
This example (based on your posted code) creates 4 layouts with 11 squares each and animates the color in each square using a timed script. Note that we need separate instances of the models for each of the GridViews within contentrepeater (otherwise it is only shown in the last view). So the example is a bit more convoluted since the item models are being created dynamically.
I should add that in a "real" application I'd use a different method of tracking the created item models instead of looking them up in the display hierarchy like I have it here. The main point this is trying to demonstrate is to manipulate the displayed items (delegates) via changes to the model data.
import QtQuick 2.9
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.3
import QtQml.Models 2.3
Pane {
id: root
width: 400
height: 650
padding: 9
// rectangle items to create per model
property int itemsPerModel: 11
// prototype object model
property Component itemModel: ObjectModel {}
// prototype model item
property Component delegate: Rectangle {
height: 30
width: 30
color: '#333333'
}
// Creates a new ObjectModel with some Rectangle items as children
function newItemModel() {
var model = itemModel.createObject(root);
for (var i=0; i < itemsPerModel; ++i)
model.append(delegate.createObject(root));
return model;
}
SequentialAnimation {
id: animate
running: true
loops: Animation.Infinite
ScriptAction {
property string nextColor: "blue"
property int nextSet: 0
property int nextItem: 0
script: {
contentrepeater.itemAt(nextSet) // the Rectangle within the GridLayout
.children[0] // the gridView within the Rectangle
.model.get(nextItem) // the model's delegate item (a Rectangle)
.color = nextColor; // set the new color on it.
// advance to next item or set of items.
nextItem = (nextItem+1) % root.itemsPerModel;
if (!nextItem)
nextSet = (nextSet+1) % contentrepeater.count;
nextColor = (nextColor === "blue" ? "orange" : nextColor === "orange" ? "white" : "blue");
}
}
PauseAnimation { duration: 100 }
}
GridLayout {
columns: 2
anchors.fill: parent
Repeater {
id: contentrepeater
model: 4
Rectangle {
color: 'red'
width: 150
height: 170
GridView {
id: gridView
anchors.fill: parent
anchors.topMargin: 10
anchors.leftMargin: 10
cellWidth: 40
cellHeight: 40
clip: true
// here we need a unique instance of the ObjectModel
model: root.newItemModel()
}
}
}
}
}

How to add children inside gridlayout dynamically in Qt quick QML code

I want to add controls at runtime, e.g. a certain number of TextField items added to a GridLayout.
I've tried to use Repeater like in the code below (some code skipped for brevity).
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
Rectangle {
width: 400
height: 400
GridLayout {
id : gridmain
Repeater {
id:gridgenerate
TextField{
id:leditfill
font.pointSize: 10
placeholderText: index +1
focus: true;
}
}
}
}
The Repeater is populated via a JS function:
function gameview() {
console.log("grid")
gridmain.rows = 10
gridmain.columns = 10
gridgenerate.model = gridmain.rows * gridmain.columns
gridgenerate.forceActiveFocus()
}
Is this the correct approach? How do I get focus on first TextField of the Gridlayout?
Almost done. Remove gridgenerate.forceActiveFocus() and set TextField focus property to true if it's the first item: index == 0.
GridLayout {
id : gridmain
Repeater {
id:gridgenerate
TextField{
id:leditfill
font.pointSize: 10
placeholderText: index +1
focus: index == 0 // only first item get focus
}
}
its' a good aproach.
you can do it dinamicaly (like a gridView)
function gameview() {
console.log("grid")
gridgenerate.model = 0 //destroy all items created by repeater
gridmain.rows = 10
gridmain.columns = 10
gridgenerate.model = buttonModel.count //add new items, using ListModel
}
ListModel {
id:buttonModel
ListElement {
color: "red"
cols:2
rows:2
name: "B1"
}
}
Repeater {
id:gridgenerate
property var listobjects:[]
Rectangle{
id:button
color :buttonModel.get(index).color
}
}

Wrong property values in Component.onCompleted

My problem is the following: I have a custom QML object based on a Rectangle, and I need to execute some javascript function with the width & height of this object when it's created.
To do that, I use Component.onCompleted to execute the javascript but in this function the width and height properties are wrong (like 0;0 or 0;-30), as if they were not yet created.
Code:
import QtQuick 2.3
import "js/kloggr.js" as Game
Rectangle {
property var kloggr: undefined
MouseArea {
anchors.fill: parent
// outputs the right values (about 400;600)
onClicked: console.log(width+";"+height);
}
Component.onCompleted: {
Game.kloggr = this;
kloggr = new Game.Kloggr(width, height);
console.log(width+";"+height); // outputs 0;-30
}
}
This object is created like this:
Kloggr {
id: kloggr
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: pauseBtn.top
}
(I've removed the irrelevant parts of the code)
So what did I do wrong, or what could I do to get the same result?
You have forget to set the width and height of your Rectangle ...
import QtQuick 2.3
import "js/kloggr.js" as Game
Rectangle {
width: 300
height: 300
property var kloggr: undefined
MouseArea {
anchors.fill: parent
// outputs the right values (about 400;600)
onClicked: console.log(width+";"+height);
}
Component.onCompleted: {
Game.kloggr = this;
kloggr = new Game.Kloggr(width, height);
console.log(width+";"+height); // outputs 0;-30
//now h + w = 300
}
}
If your use anchors, change your Rectangle by Item, for exemple
import QtQuick 2.3
import "js/kloggr.js" as Game
Item{
//without W and Height if you don't use the designer, if you use the designer you should set a default size
property var kloggr: undefined
Rectangle{
anchors.fill : parent
MouseArea {
anchors.fill: parent
// outputs the right values (about 400;600)
onClicked: console.log(width+";"+height);
}
Component.onCompleted: {
Game.kloggr = this;
kloggr = new Game.Kloggr(width, height);
console.log(width+";"+height); // outputs 0;-30
}
}//end of rectangle
} //end of item
I did not find out it if was a bug or something but I found a workaround: instead of using Component.onCompleted I used onVisibleChanged:
onVisibleChanged: {
if (visible && kloggr === undefined) {
Game.kloggr = this;
kloggr = new Game.Kloggr(width, height);
}
}
It seems that the width and height properties are only valid when the object is set to visible...
Thank you #yekmen for your help

QML iterating over custom elements and calling function

I have a custom element called MenuButton:
import QtQuick 1.1
import VPlay 1.0
Image {
property alias text: buttontext.text
property alias mouseArea: area
property alias fontBold: buttontext.font.bold
property alias textSize: buttontext.font.pixelSize
id: button
source: "img/cloudButton.png"
opacity: 1
Text {
id: buttontext
color: "black"
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
anchors.leftMargin: 50
font.bold: true
}
MouseArea {
id: area
anchors.fill: parent
onPressed: button.opacity = 0.7
onReleased: button.opacity = 1.0
onCanceled: button.opacity = 1.0
}
function doStuff {
// do something here
}
width: 200
height: 60
}
Now, in my main View, I have a Column with 5 of those MenuButtons. And I want to iterate over them and call the function doStuff(). How do I do that?
I tried with column.childAt(i) and stuff like that, nothing worked.
MainView.qml
Rectangle {
width: 480; height: 320
// HERE IS MY PROBLEM, how do I iterate over all my elements in the column?
function update() {
for(var i = 0; i < 5; i++) {
column.childAt(i).doStuff(); // THIS IS WHAT I WANT TO DO
}
}
Column {
id: column
spacing: 5
anchors.centerIn: parent
Repeater {
id: repeater
model: 5
MenuButton {
id: levelbutton
text: "Level " + (modelData+1);
source: "img/cloud4.png"
}
}
}
}
The problem is in my update function in the MainView.qml
I dont know how to iterate over the elements and call the doStuff() function.
You may use Component.onCompleted attached signal, like this:
import QtQuick 1.0
Rectangle {
height: 600
width: 600
Repeater {
model: 5
Item {
Component.onCompleted: console.log('Component ' + index + ' completed!')
}
}
}
However, please consider, that this imperative operation is not good, because it will be called all time after model update. Probably you have problem X and asking how to get Y, that (you think) will solve your X?
From what I've seen in the source code in the QDeclarativePositioners class you cannot access the children elements!
But you could turn the way you call your doStuff() method: when do you want it to be called? After some time has passed (then add a Timer element to your MenuButton), or when a signal occurs? In the latter case, you could use the Connections element and listen to the signal beign emitted in your calling qml file where you use the Column and Repeater.
Cheers, Chris
You can access the children of an element via the children property that exists on all QtObjects. It contains an array of child elements and can be freely acccessed in javascript.
eg. element.children[0].doStuff()
Generally speaking, you should avoid actions that require you to manually iterate over the children. However, if you are attempting to write code that generically calls something on each of the children you do not always have a choice.

Resources