2016-10-10 136 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()应该帮助那里。