如何在QML中实例化多个自定义骰子组件并实现网格布局展示
问题原因
你当前代码仅显示单个骰子的核心原因是所有Dice实例都设置了anchors.centerIn: parent,6个组件全部重叠在窗口中心,仅能看到最后渲染的那一个实例。
解决步骤
- 给Dice自定义组件添加隐式尺寸声明,方便布局容器自动计算组件占位大小
- 在父QML中使用GridLayout包裹Repeater,自动排列6个骰子组件
修改后代码
Dice.qml
//Dice.qml import QtQuick import QtQuick.Layouts Item { property int num_dots id: container // 新增隐式尺寸,和内部骰子矩形大小绑定 implicitWidth: diceRect.width implicitHeight: diceRect.height function getDots(num) { var data; switch (num) { case 1: data = ["white", "white", "white","white", "black", "white","white", "white", "white"]; break; case 2: data = ["black", "white", "white", "white","white", "white","white", "white", "black"]; break; case 3: data = ["black", "white", "white", "white","black", "white","white", "white", "black"]; break; case 4: data = ["black", "white", "black","white", "white", "white","black", "white", "black"]; break; case 5: data = ["black", "white", "black","white", "black", "white","black", "white", "black"]; break; case 6: data = ["black", "white", "black","black", "white", "black","black", "white", "black"]; break; default: data = ["white", "white", "white", "white", "white", "white", "white", "white", "white"]; } return data; } Rectangle { id: diceRect // 新增id方便根节点绑定尺寸 width: 150 height: 150 color: "white" border.color: "black" border.width: 5 radius: 10 anchors.centerIn: parent GridLayout { rows: 3; rowSpacing: 5; columns: 3; columnSpacing: 5; anchors.centerIn: parent Repeater { model: container.getDots(container.num_dots) Rectangle { width: 40 height: 40 color: modelData radius: 20 } } } } }
父QML文件
import QtQuick import QtQuick.Window import QtQuick.Controls import QtQuick.Layouts Window { id: root width: 640 height: 480 visible: true title: qsTr("Dice") // GridLayout作为骰子排列容器 GridLayout { anchors.fill: parent anchors.margins: 20 columns: 3 // 3列时6个骰子自动排成2行,如需3行2列可改为2 rowSpacing: 20 columnSpacing: 20 Repeater { model: 6 Dice { num_dots: index+1 // 移除原有的anchors.centerIn,由GridLayout自动分配位置 } } } }
效果参考

内容的提问来源于stack exchange,提问作者Speccy
相关产品推荐
相关产品推荐

