QML组件:显示消息的单例悬浮窗组件

代码:

pragma Singleton  //定义此组件为单例组件
import QtQuick 2.12
import QtGraphicalEffects 1.12
import QtQuick.Window 2.12

//显示临时信息的弹窗
Window
{
    id: root
    visible: false
    flags: Qt.FramelessWindowHint | Qt.Window
    color: "#00000000"

    Rectangle
    {
        id: contextRect
        anchors.fill: parent
        anchors.margins: 20
        radius: 12

        Text
        {
            id:infoText
            color: "#222222"
            font.pixelSize: 22
            font.bold: true;

            padding:20
            clip: false

            anchors.fill: parent

            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
        }
    }

    DropShadow
    {
       anchors.fill: contextRect
       horizontalOffset: -5
       verticalOffset: -5
       radius: 12
       color: "#20000000"
       source: contextRect
       transparentBorder :true
    }
    DropShadow
    {
        anchors.fill: contextRect
        horizontalOffset: 5
        verticalOffset: 5
        radius: 12
        color: "#20000000"
        source: contextRect
        transparentBorder :true
    }
    DropShadow
    {
        anchors.fill: contextRect
        horizontalOffset: 5
        verticalOffset: -5
        radius: 12
        color: "#20000000"
        source: contextRect
        transparentBorder :true
    }
    DropShadow
    {
        anchors.fill: contextRect
        horizontalOffset: -5
        verticalOffset: 5
        radius: 12
        color: "#20000000"
        source: contextRect
        transparentBorder :true
    }

    Timer
    {
        id:timer
        interval: 3000
        repeat:false
        onTriggered: root.close()
    }

    function setMsgInfo(info)
    {
        infoText.text = info
        root.width = 1
        root.height = 1
        root.x = Screen.desktopAvailableWidth + 100
        root.y = Screen.desktopAvailableHeight + 100
        root.showNormal()

        root.width = infoText.contentWidth + 100
        root.height = infoText.contentHeight + 80

        root.x = (Screen.desktopAvailableWidth - root.width)/2
        root.y = (Screen.desktopAvailableHeight - root.height) * 0.2

        timer.start()
    }
}

注册为单例:

    qmlRegisterSingletonType(QUrl("qrc:/Control/ShowTemporaryMessage.qml"), "SingletonComponent", 1, 0, "HoverShowMessage" );

使用:

import SingletonComponent 1.0

...

    HoverShowMessage.setMsgInfo(msg)

你可能感兴趣的:(#,QML编写自定义控件,qml)