Reputation: 1514
I'm working with Qt 5.4. I have a Qt Quick Project and I'm using QML. For some reasons I have to use the Canvas
element to draw a tree. In some cases, my tree is larger than my Canvas element (400x800
). So, my question is: how can I auto-fit my canvas depending my tree height?, there is a scrollbar or something like that?
Thanks!
Upvotes: 0
Views: 600
Reputation: 12854
You can put your Canvas
inside ScrollView
or Flickable
, for example:
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();
}
}
}
}
}
}
Remove ScrollView
item if you need only Flickable
. The Canvas
updates itself to max width/height.
Upvotes: 1