我有一个正在运行的着色器,我希望能够在按下按钮时禁用着色器。我想禁用它,这样它就不会使用任何额外的资源。我怎样才能做到这一点?这里我有一个着色器缓慢淡入和淡出的示例,我想在您单击左上角的按钮时禁用着色器。现在,我得到这个例外:
ShaderEffect: Property 'source' is not assigned a valid texture provider (std::nullptr_t).
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
width: 1024
height: 600
visible: true
property bool shaderEnabled: true
Rectangle {
id: rect
anchors.fill: parent
color: "gray"
layer.enabled: shaderEnabled
Text {
anchors.centerIn: parent
text: qsTr("Hello")
font.pixelSize: 40
color: "blue"
}
}
MouseArea {
anchors.fill: parent
onClicked: {
if (shader.opacity > 0) {
shader.opacity = 0
console.log("Hiding")
} else {
shader.opacity = 1
console.log("Showing")
}
}
}
Button {
id: shaderButton
text: shaderEnabled ? "Disable shader" : "Enable shader"
onClicked: {
shaderEnabled = !shaderEnabled
}
}
ShaderEffect {
id: shader
anchors.fill: parent
property variant source: shaderEnabled ? rect : null
Behavior on opacity { PropertyAnimation {} }
opacity: 0
fragmentShader: "
varying highp vec2 qt_TexCoord0;
uniform sampler2D source;
uniform lowp float qt_Opacity;
void main() {
gl_FragColor = texture2D(source, qt_TexCoord0) * vec4(1.0, 1.0, 0.0, 1.0) * qt_Opacity;
}"
}
}
向 ShaderEffect 添加
visible: ShaderEnabled
似乎可行,但我仍然看到错误消息,这让我相信它仍在使用资源。使用Loader
会有帮助吗?