qt - 如何将不透明蒙版应用于 QML 项目?

标签 qt qml qtquick2 qt-quick qtquickcontrols

我想要的外观和感觉是有一个纯色按钮,上面有像“Hello World”这样的文本,文本是完全透明的,背景通过按钮显示。

换句话说,将文本作为按钮元素上的透明蒙版。

最佳答案

这是一种方法:

// TB.qml
MouseArea {
  width: txt.contentWidth + 20
  height: txt.contentHeight + 10
  property alias text: txt.text
  property alias color: sh.color
  ShaderEffect {
    id: sh
    anchors.fill: parent
    property color color: "red" 
    property var source : ShaderEffectSource {
      sourceRect: Qt.rect(0, 0, sh.width, sh.height)
      sourceItem: Item {
        width: sh.width
        height: sh.height
        Text {
          id: txt
          anchors.centerIn: parent
          font.bold: true
          font.pointSize: 30
          text: "test"
        }
      }
    }
    fragmentShader:
        "varying highp vec2 qt_TexCoord0;
           uniform highp vec4 color;
           uniform sampler2D source;
           void main() {
               gl_FragColor = color * (1.0 - texture2D(source, qt_TexCoord0).w);
           }"
  }
}

使用它:
  TB {
    text: "HELLO WORLD!!!"
    color: "red"
    onClicked: console.log("hi world")
  }

结果:

enter image description here

按钮是红色的,灰色背景中的文本是灰色的,它将准确地显示按钮下方的任何内容。

显然,该按钮是简陋的,但该示例足以让您开始并根据您的需要实现某些东西。

这里的关键元素是自定义着色器,这是一个非常基本的着色器 - 它为每个片段着色并将蒙版应用为 alpha。显然,您可以使用 ShaderEffectSource将任何 QML 项转换为纹理,并替换 ShaderEffectSource与另一个 sampler 2D并以您想要的任何方式混合两种纹理,使用 alpha channel 或任何 RGB(如果您使用灰度蒙版)进行剪切。与相当有限的 OpacityMask 不同元素,这实际上将切入并显示下面的任何内容。

关于qt - 如何将不透明蒙版应用于 QML 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903639/

相关文章:

c++ - 初始化 QString 的最佳方法

c++ - 在 C++ 中复制到剪贴板?

qt - QML中的if语句

qt - 如何在 QML 中对中继器的委托(delegate)应用 Qt 图形效果

c++ - 如何将 Qt 类中声明的结构传递给同一类的函数?

qt - 如何提取路径的文件名

qt - QListView外部drop不起作用

qt - QML 3D - 更改在 UI 中呈现的模型的大小(扩大/缩小)以适应当前窗口

c++ - 在 bb10 上实现后退按钮

qt - onClicked 和 onDoubleClicked 都发生在 QML 中