【问题标题】:Transparent button text over the background背景上的透明按钮文本
【发布时间】:2016-10-10 13:35:07
【问题描述】:

我正在尝试在 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"
                }
            }
        }
    }

我想要的只是在悬停状态的按钮中有透明文本。文本应该具有背景颜色。示例:

更新。我需要这个在没有着色器的情况下在慢速电脑上工作。

【问题讨论】:

  • this post可以帮到你吗?
  • @user2436719 我需要这个例子来在一台装有旧集成显卡的慢速电脑上工作,我的程序会有很多按钮。没有着色器有没有能力做到这一点?
  • @Pillar - OpenGL 中的所有内容都已使用着色器。着色器本身是微不足道的,几乎不比平面颜色着色慢。不,如果不使用着色器,您将无法在 OpenGL 中做任何事情。 QML 使用 OpenGL。无论哪种方式,您最终都会使用着色器。
  • TL;DR:如果您使用的是 Qt Quick,那么您已经在使用着色器了。着色器在速度较慢的 PC 上使其速度更快,因为它们专门用于非常快速执行这种重复处理 - 至少比 CPU 可以执行的速度快一个数量级。

标签: qt qml


【解决方案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() 应该会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多