首页 > 解决方案 > 如何使从 qml 组件初始化的 QWidget 的背景透明?

问题描述

我正在编写自定义工具提示。为了显示 DropShadow,实际大小control应该更大。

Item {
    id: control
    width: tipText.width + 5
    height: tipText.height + 5
    ...
    Rectangle {
        id: background
        height: tipText.height
        width: tipText.width
        Text {
            id: tipText
            ...
        }
    }

    Rectangle {
        id: shadow
        height: tipText.height - 3
        width: tipText.width - 3
        z: -1
        color: "white"
        anchors.bottom: background.bottom
        anchors.right: background.right
        layer.enabled: true
        layer.effect: DropShadow {
            ...
        }
    }
}

在 cpp 文件中:

QQuickView* view = new QQuickView;
view->setSource(QUrl("qrc:/impl/my.qml"));
        
QWidget* cont = QWidget::createWindowContainer(view,  nullptr);
        
cont->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);

现在看起来像这样:

我想知道如何使背景透明。(此外,我试过cont->setAttribute(Qt::WA_TranslucentBackground)了,它只是让一切变得透明)

标签: qtqmlqt6

解决方案


我想您也必须将窗口颜色设置为透明。实际上,这对我有用:

Window {
    visible: true
    id: window
    flags: Qt.ToolTip | Qt.FramelessWindowHint | Qt.WA_TranslucentBackground
    width: background.width + 40
    height: background.height + 40
    color: "#00000000"
    x: (Screen.width - window.width) / 2
    y: (Screen.height - window.height) / 2

    Rectangle {
        id: background
        height: 40
        width: 100
        anchors.centerIn: parent
        layer.enabled: true
        layer.effect: DropShadow {
            anchors.fill: background
            horizontalOffset: 2
            verticalOffset:2
            radius: 10.0
            samples: 10
            color: "lightgrey"
            source: background
        }
    }

    Rectangle {
        anchors.fill: parent
        anchors.margins: 20
        color: "white"
        anchors.centerIn: parent

        Text {
            anchors.fill: parent
            text: "Hello, world!"
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
        }

        MouseArea {
            anchors.fill: parent
            onClicked: window.close();
        }
    }
}

推荐阅读