我正在使用Qt 5.4。我有一个Qt快速项目,我正在使用QML。出于某些原因,我必须使用Canvas
元素来绘制树。在某些情况下,我的树比我的Canvas元素(400x800
)大。所以,我的问题是:我如何根据我的树高自动调整我的画布?,有一个滚动条或类似的东西?
谢谢!
答案 0 :(得分:1)
您可以将Canvas
置于ScrollView
或Flickable
内,例如:
ApplicationWindow {
width: 200;
height: 200;
id: root
ScrollView {
anchors.fill: parent
Flickable {
anchors.fill: parent
contentWidth: canvas.width
contentHeight: canvas.height
Canvas {
id: canvas
width: 300
height: 300
property int maxX: 0
property int maxY: 0
property var coords: getCoords()
function getCoords() {
var retval = [];
for(var i = 0;i < 10;i ++) {
var x = Math.round(Math.random() * 1000);
var y = Math.round(Math.random() * 1000);
retval.push(x);
retval.push(y);
}
return retval;
}
onPaint: {
var context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0,0,canvas.width,canvas.height);
context.moveTo(canvas.width / 2, canvas.height / 2);
context.strokeStyle = Qt.rgba(0,0,255,0.5);
context.lineWidth = 5;
context.beginPath();
for(var i = 0;i < coords.length;i += 2) {
context.lineTo(coords[i],coords[i + 1]);
if(coords[i] > maxX) maxX = coords[i];
if(coords[i + 1] > maxY) maxY = coords[i + 1];
}
context.closePath();
context.stroke();
}
onPainted: {
if(canvas.width < maxX || canvas.height < maxY) {
canvas.width = maxX;
canvas.height = maxY;
update();
}
}
}
}
}
}
如果您只需要ScrollView
,请移除Flickable
项。 Canvas
将自身更新为最大宽度/高度。