QT quick2 qml dynamically changing GridView columns

I used GridView to display ListModel. I initially set cellWidth to:

cellWidth = grid.width/3

to create a grid of three columns. then I want to change the number of columns to 2, so I set cellWidth to:

 cellWidth = grid.width/2 

GridView screen has changed. But when I resize the container desktop window, the cells in the gridview will no longer resize.

What should I do to make it right?

Please review the following code:

 import QtQuick 2.1 import QtQuick.Controls 1.0 import QtQuick.Window 2.0 ApplicationWindow { title: qsTr("Hello World") width: 640 height: 480 menuBar: MenuBar { Menu { title: qsTr("File") MenuItem { text: qsTr("2 columns") onTriggered: grid.cellWidth = grid.width/2; } MenuItem { text: qsTr("3 columns") onTriggered: grid.cellWidth = grid.width/3; } } } GridView { id: grid anchors.fill: parent cellWidth: width / 3; cellHeight: 300; model: ListModel { ListElement { name: "Apple" cost: 2.45 } ListElement { name: "Orange" cost: 3.25 } ListElement { name: "Banana" cost: 1.95 } } delegate : Rectangle { //anchors.fill: parent width: grid.cellWidth height: grid.cellHeight border.color: "green" border.width: 2 color: "red" } } } 
+4
source share
2 answers

I solved the problem by defining onWidthChanged from gridview.

 import QtQuick 2.1 import QtQuick.Controls 1.0 import QtQuick.Window 2.0 ApplicationWindow { title: qsTr("Hello World") width: 640 height: 480 id: appwnd property int columns : 3; menuBar: MenuBar { Menu { title: qsTr("File") MenuItem { text: qsTr("2 columns") onTriggered: { columns = 2; grid.cellWidth = grid.width/columns; } } MenuItem { text: qsTr("3 columns") onTriggered: { columns = 3; grid.cellWidth = grid.width/columns; } } } } GridView { id: grid anchors.fill: parent cellWidth: width / 3; cellHeight: 300; model: ListModel { ListElement { name: "Apple" cost: 2.45 } ListElement { name: "Orange" cost: 3.25 } ListElement { name: "Banana" cost: 1.95 } } delegate : Rectangle { //anchors.fill: parent width: grid.cellWidth height: grid.cellHeight border.color: "green" border.width: 2 color: "red" } onWidthChanged: { grid.cellWidth = grid.width/appwnd.columns; } } } 
+8
source

The problem you are facing is that the bindings are not automatically configured when writing JavaScript (what you do in the onTriggered signal onTriggered ).

You can perform bindings in Javascript (as opposed to binding properties of pure QML) with Qt.binding() :

 onTriggered: { columns = 2; grid.cellWidth = Qt.binding(function() { return grid.width/columns; }); } 

While your onWidthChanged handler onWidthChanged working, it is a cleaner solution.

For more information on how this works, see http://doc.qt.io/qt-5/qtqml-syntax-propertybinding.html#creating-property-bindings-from-javascript .

0
source

Source: https://habr.com/ru/post/1496496/


All Articles