QML如何绘制不同于grabToImage()

Pro*_*mit 8 qt qml

是否有任何可能的方法使grabToImage()缓冲区与GUI中显示的不同?我ChartView在GUI中使用没有图例,并希望将其导出为PNG图例.所以我尝试:

chartView.legend.visible = true
chartView.update()
chartView.grabToImage(function(result) {
    console.log("grabbed")

    var path = filename.toString().replace(/^(file:\/{2})/,"");
    console.log(path + result.saveToFile(path));
    chartView.legend.visible = false
    update();
});
Run Code Online (Sandbox Code Playgroud)

但是这些更新只有在控件出来之后才会发生,因此我不会在PNG中绘制传奇.另外,我希望图例的外观对用户来说是不可察觉的.在QML中有没有办法做到这一点?

der*_*erM 5

我不确定我是否正确。

我的建议是,不要抓住Item您显示的内容,而是复制它的副本,然后根据需要进行修改。在此处
复制并不意味着您有两次相同的对象,而是使用渲染了两次ShaderEffectSource。在将其抓取ShaderEffectSource到图像之前,您可以添加任何喜欢的内容。

在我的示例中,我显示了一个Rectangle具有良好渐变的简单样式。我保存的内容与“我是传奇” Rectangle扩展的内容相同Text。用户在任何时候都不会在视图中看到该文本。

Rectangle {
    id: commonView
    width: 200
    height: 200
    gradient: Gradient {
        GradientStop { position: 0; color: 'steelblue' }
        GradientStop { position: 1; color: 'orange' }
    }
    MouseArea {
        anchors.fill: parent

        // don't grab the rectangle itself.
        onClicked: legendView.grabToImage(function(result) {
            console.log(result.saveToFile("something.png"));
        });
    }
}

ShaderEffectSource {
    id: legendView
    visible: false // Does not need to be shown.
    sourceItem: commonView
    width: 200
    height: 200
    Text {
        anchors {
            right: parent.right
            bottom: parent.bottom
        }
        text: 'I am legend'
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过仅ShaderEffectSource在需要时才激活甚至创建来优化性能。

您可以使用ShaderEffectSource.live-property禁用其更新。然后使用scheduleUpdate()触发更新。

可能看起来像这样:

Rectangle {
    id: commonView
    width: 200
    height: 200
    gradient: Gradient {
        GradientStop { position: 0; color: 'steelblue' }
        GradientStop { id: gs1; position: 1; color: 'orange' }
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            gs1.position -= 0.1
            legendView.save()
        }
    }
}

ShaderEffectSource {
    id: legendView
    y: 200
    visible: false // Do not render it (will only be rendered when called grapToImage()
    sourceItem: commonView
    width: 200
    height: 200
    live: false // Will only be updated, when explicitly called for
    function save() {
        console.log('Schedule Save')
        scheduleUpdate() // explicitly update. grabToImage() will force rendering afterwards.
        legendView.grabToImage(function(result) {
                        console.log(result.saveToFile("something" +gs1.position.toFixed(1) + ".png"));
                    })
    }

    // Put additional stuff on it.
    Text {
        anchors {
            right: parent.right
            bottom: parent.bottom
        }
        text: 'I am legend!'
    }
}
Run Code Online (Sandbox Code Playgroud)