如何在QML中截取特定项目的屏幕截图?

Aqu*_*irl 0 qt qml qt5 qtquick2

我知道如何在QML中截取整个窗口的截图.

Video在QML窗口中有一个元素.该视频显示在一个Rectangle.

什么是采取截图的方式Rectangle,而不是整个窗口?

tro*_*ane 5

这是一个非常有趣的问题.作为一个快速和有效的解决方案,我可以建议你使用grabToImage方法Item.它将第一个参数作为回调函数,第二个参数作为要保存的路径.

我写了一个小函数来抓取任何Item:

// what -- name of item needed to be grabbed
// where -- string
function render(what, where) {
    // Find existent item with given name `what`
    var i = 0
    var found = false
    for (i = 0; i < window.contentItem.children.length; i++) {
        if (window.contentItem.children[i].objectName === what) {
            // We found respective item
            found = true
            break
        }
    }
    if (found) {
        console.log("We found item " + what + ". Grabbing it to " + where)
        var item = window.contentItem.children[i]
        // Grab image and save it (via callback f-ion)
        item.grabToImage( function(result) { result.saveToFile(where) })
    } else {
        console.warn("No item called " + what)
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你可以像Qt(使用QMetaObject::invokeMethod)一样在QML/QtQuick端使用它.


还有QQuickItem::grabToImage方法,但我很高兴看到任何适当的使用示例.


另一种抓取方式是ShaderEffectSource按照您的意愿使用和使用.


我上面写的所有内容都是作为一个项目编写的,位于github上.代码被评论,所以希望一切都清楚.你可以接受并做一些黑客攻击.欢迎提出拉动请求.