如何使用javascript在QML中创建这样的东西?
其实我知道如何在QML中创建矩形但是想要做这样的事情.QML画布可以是任何大小,但是无论何时加载QML部分,都会生成具有随机大小和颜色的多个正方形而不重叠.当我尝试这样做时,矩形以列表形式生成.我是一个Web开发人员(ruby on rails oriented)但是对这些javascript的东西很新.任何帮助将不胜感激.
正如@ddriver已经注意到的那样,最简单的决定是遍历所有孩子,找到一个新的矩形空间.
Rectangle {
id: container
anchors.fill: parent
property var items: [];
Component {
id: rect
Rectangle {
color: Qt.rgba(Math.random(),Math.random(),Math.random(),1);
border.width: 1
border.color: "#999"
width: 50
height: 50
}
}
Component.onCompleted: {
var cnt = 50;
for(var i = 0;i < cnt;i ++) {
for(var t = 0;t < 10;t ++) {
var _x = Math.round(Math.random() * (mainWindow.width - 200));
var _y = Math.round(Math.random() * (mainWindow.height - 200));
var _width = Math.round(50 + Math.random() * 150);
var _height = Math.round(50 + Math.random() * 150);
if(checkCoord(_x,_y,_width,_height)) {
var item = rect.createObject(container,{ x: _x, y: _y, width: _width, height: _height });
container.items.push(item);
break;
}
}
}
}
function checkCoord(_x,_y,_width,_height) {
if(container.items.length === 0)
return true;
for(var j = 0;j < container.items.length;j ++) {
var item = container.children[j];
if(!(_x > (item.x+item.width) || (_x+_width) < item.x || _y > (item.y+item.height) || (_y+_height) < item.y))
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
是的,这不是那么明智的解决方案,但它仍然可以改进.
| 归档时间: |
|
| 查看次数: |
2705 次 |
| 最近记录: |