Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Position of an element in nested canvases in QML



  • Hi all quick question, for QML. If you have nested canvases and say a rectangle in the nested canvas, why is the x and y value not relative to the parent canvas but rather the root canvas?
    For example the following, the rectangle draws at the top left of the big black rectangle rather than 10 pixels inside the red canvas.
    Is there a way to get it so the x and y are relative to the parent/nested canvas?

    import QtQuick 2.0
    import org.kde.plasma.core 2.0 as PlasmaCore
    
    Canvas {
        id: page
        width: 600
        height: 600
    
        onPaint: {
            var ctx = getContext("2d");
            ctx.fillStyle = Qt.rgba(0, 0, 0, 1);
            ctx.fillRect(0,0,width,height);
        }
    
        Canvas {
            id: building_00_canvas
            width: 200
            height: 200
    
            Rectangle{id: buildrow1; width: 50; height: 50; color: "#0000FF"; x: 10; y:10;}
    
    
            onPaint: {
                var ctx = getContext("2d");
                ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
                ctx.fillRect(100,100,width,height);
            }
        }
    }
    

  • Moderators

    @FrostedCookies said in Position of an element in nested canvases in QML:

    why is the x and y value not relative to the parent canvas but rather the root canvas?

    because it isn't.

    And you see that, as soon as you actually paint the whole 2nd canvas

    onPaint: {
                var ctx = getContext("2d");
                ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
                ctx.fillRect(0,0,width,height);// instead of ctx.fillRect(100,100,width,height); 
            }
    

Log in to reply