qtqmlqtquick2qimageqquickitem

Qt : How to grab a snapshot of a QQuickItem leaving out its child QQuickItems from the grabbed result


My question is a follow up on this discussion.

Yes. Following way of grabToImage can get me a snapshot of any particular QQuickItem like parent_rect below.

Rectangle {
    id: parent_rect
    width: 400
    height: 400

    Rectangle {
        id: child_rect1
        width: parent.width/4
        height: parent.height/4
    }

    Rectangle {
        id: child_rect2
        width: parent.width/4
        height: parent.height/4
    }
}
// ...
parent_rect.grabToImage(function(result) {
                       result.saveToFile("something.png");
                   });

Problem:
But this grabToImage gets me the snapshot of the all its children as well namely child_rect1 and child_rect2.

Question:
How can I get the snapshot of parent_rect only without getting its children add into the returned result?


Solution

  • One possible solution is to hide the children and then restore visibility.

    Example:

    import QtQuick 2.9
    import QtQuick.Window 2.2
    
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
    
        function grabWithoutChildren(item, filename){
            var isVisibleList = []
            var i
            for(i in item.children){
                isVisibleList[i] = item.children[i].visible
                item.children[i].visible = false
            }
    
            item.grabToImage(function(result) {
                result.saveToFile(filename)
                for(i in item.children){
                     item.children[i].visible = isVisibleList[i]
                }
            })
        }
    
        Rectangle {
            id: parent_rect
            width: 400
            height: 400
            color: "red"
    
            Rectangle {
                id: child_rect1
                width: parent.width/4
                height: parent.height/4
                color: "blue"
            }
    
            Rectangle {
                id: child_rect2
                x: 10
                y: 10
                width: parent.width/4
                height: parent.height/4
                color: "green"
    
                Rectangle{
                    x:50
                    y:50
                    width: 100
                    height: 100
                    color: "white"
                }
            }
        }
    
        Component.onCompleted: grabWithoutChildren(parent_rect, "something.png")
    }