gpt4 book ai didi

c++ - QT quick2 qml动态改变GridView列

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:50 27 4
gpt4 key购买 nike

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

cellWidth = grid.width/3

创建一个 3 列的网格。然后我想将列数更改为 2,因此我将 cellWidth 设置为:

cellWidth = grid.width/2

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"
}
}
}

最佳答案

我已经通过定义 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;
}
}
}

关于c++ - QT quick2 qml动态改变GridView列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18179607/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com