QML - 具有半径的矩形的LinearGradient?

时间:2018-03-02 19:07:34

标签: qt qml

我有一个带圆角(半径)的简单矩形,但想为它的背景颜色应用渐变。

Rectangle {
    id: rect
    width: 200
    height: 200

    radius: 20

    LinearGradient {
        anchors.fill: parent
        start: Qt.point(0,parent.height/2)
        end: Qt.point(parent.width,parent.height/2)
        gradient: Gradient {
            GradientStop { position: 0.0; color: "red" }
            GradientStop { position: 1.0; color: "green" }
        }
    }
}

我在想OpacityMask可能会有所帮助吗?不过,我试过用一个无济于事。我想知道我是否只是缺少某些东西,或者解决方案是否更复杂。

3 个答案:

答案 0 :(得分:2)

Qt图形效果很强大,但功耗很大。只要有可能,最好继续使用Qt Quick核心原语。也许它只是简化的测试用例,现实生活中的用例更加复杂,但是显示的测试用例可以通过简单的圆形,旋转和渐变填充来实现Shop here cheap

Rectangle

要备份性能声明,让我们看看使用QML bench基准测试工具测量的一些数字。我们使用Rectangle { id: rect width: 200 height: 200 radius: 20 rotation: -90 gradient: Gradient { GradientStop { position: 0.0; color: "red" } GradientStop { position: 1.0; color: "green" } } } OpacityMask对使用LinearGradientRectangle的解决方案进行基准测试,使用普通GradientID: OS: macOS High Sierra (10.13) QPA: cocoa GL_VENDOR: Intel Inc. GL_RENDERER: Intel HD Graphics 5000 OpenGL Engine GL_VERSION: 2.1 INTEL-10.30.14 running: lineargradient_opacitymask.qml 11 frames 11 frames 11 frames 11 frames 11 frames Average: 11 frames;; MedianAll=11; StdDev=0, CoV=0 All done... 。这些基准测试是在最新的Qt 5.10.1版本上运行的,这是一款老式的MacBook Air(Intel Core i5-4260U,Intel HD 5000,macOS 10.13)。

LinearGradient + OpacityMask

ID:          
OS:          macOS High Sierra (10.13)
QPA:         cocoa
GL_VENDOR:   Intel Inc.
GL_RENDERER: Intel HD Graphics 5000 OpenGL Engine
GL_VERSION:  2.1 INTEL-10.30.14
running: rect_gradient.qml
    332 frames
    331 frames
    334 frames
    313 frames
    331 frames
    Average: 328.2  frames;; MedianAll=331; StdDev=8.58487, CoV=0.0261574
All done...

Rectangle::gradient

{{1}}

答案 1 :(得分:1)

嗯,不透明蒙版应该可以使用,但是你必须隐藏圆角的来源才能看到,否则它们会从背面显示......

  Rectangle {
    id: rect
    width: 200
    height: 200    
    // radius: 20 - redundant
    visible: false // hide it!!!

    LinearGradient {
      anchors.fill: parent
      start: Qt.point(0,parent.height/2)
      end: Qt.point(parent.width,parent.height/2)
      gradient: Gradient {
        GradientStop { position: 0.0; color: "red" }
        GradientStop { position: 1.0; color: "green" }
      }
    }
  }

  OpacityMask {
    anchors.fill: rect
    source: rect
    maskSource: Rectangle {
      width: 200
      height: 200
      radius: 20
    }
  }

答案 2 :(得分:0)

设置LinearGradient的source属性,它应该解决这个问题:

Rectangle {

    id: rect
    width: 200
    height: 200
    radius: 20

    LinearGradient {
        anchors.fill: parent
        source: rect
        start: Qt.point(0,parent.height/2)
        end: Qt.point(parent.width,parent.height/2)
        gradient: Gradient {
            GradientStop { position: 0.0; color: "red" }
            GradientStop { position: 1.0; color: "green" }
        }
    }
}
相关问题