2016-10-10 133 views
0

我正在嘗試在qml中創建透明文本。 我有一個自定義按鈕:背景透明按鈕文本

ApplicationWindow { 
    visible: true 
    width: 320 
    height:240 
    style: ApplicationWindowStyle { 
      background: Image { // paste any url here 
       source: "https://t4.ftcdn.net/jpg/01/05/18/57/240_F_105185755_w384KDBvemK5Mn4oXzrWbCz9SRvHuDIh.jpg" 
      } 
    } 
    Button 
    { 
     anchors.centerIn: parent 
     style: ButtonStyle 
     { 
      padding 
      { 
       left: 16 
       right: 16 
       top: 8 
       bottom: 8 
      } 

      background: 
       Rectangle 
       { 
        antialiasing: true 
        color: control.pressed ? "#d1d1d1" : control.hovered ? "#666" : "transparent" 
        border.color: "white" 
        radius: height/2 
        border.width: 1 
       } 

      label: 
       Text 
       { 
        text: "buttonText" 
        color: control.pressed ? "white" : control.hovered ? "#00000000" : "white" 
       } 
      } 
     } 
    } 

所有我想要的是有懸停狀態按鈕透明文本。文本應該有背景的顏色。例如:Example

upd。我需要這個在沒有着色器的慢電腦上工作。

+2

可以[這篇文章](http://stackoverflow.com/questions/39903639/how-to-apply-opacity-mask-to-a-qml-item)幫助你嗎? – user2436719

+0

@ user2436719我需要這個例子來使用舊的集成顯卡慢速電腦上工作,我的程序會有很多按鈕。有沒有沒有着色器的能力呢? – Pillar

+2

@Pillar - OpenGL中的所有東西都已經使用着色器。着色器本身是微不足道的,幾乎比平淡的陰影更慢。不,你不能在不使用着色器的情況下在OpenGL中做任何事情。 QML使用OpenGL。不管怎樣,你最終都會使用着色器。 – dtech

回答

1

一種選擇是使用自定義QQuickPaintedItem並使用QPainterPath來繪製「文字形狀的洞」。

基本上是這樣的

void MyItem::paint(QPainter *painter) 
{ 
    QPainterPath path; 
    path.addRect(0, 0, width(), height()); 
    path.addText(textX, textY, font, yourText); 

    painter->setBrush(yourBackgroundColor); 
    painter->setPen(Qt::transparent); 
    painter->drawPath(path); 
} 

位置,即textXtextY,將不得不手動計算我很害怕,但QFontMetrics::boundingRect()應該幫助那裏。