QT quick2 qml动态更改GridView列

Bre*_*t81 4 c++ qml qtquick2

我使用GridView来显示ListModel.最初我将cellWidth设置为:

cellWidth = grid.width/3

创建一个3列网格.然后我想将列数更改为2,所以我将cellWidth设置为:

cellWidth = grid.width/2
Run Code Online (Sandbox Code Playgroud)

GridView的显示改变了.但是,当我调整容器的桌面窗口大小时,gridview中的单元格将不再更改大小.

我该怎么做才能使它正确?

请看下面的代码:

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"
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Bre*_*t81 8

我通过定义gridview的onWidthChanged解决了这个问题.

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)