【Qt6】【QML】【教程】创建通知弹窗
整体的代码不是很难,必要的注释都写在代码里了。需要注意的是
-
PopWindow.qml 的Window 属性的x y 可以被外部调用的时候被覆盖. -
窗口的大小根据Loader 里面content_pop_window 的内容大小改变
import QtQuick
import QtQuick.Controls 2.5
import QtQuick.Window 2.3
Window{
id: pop_window
visible: false
color: "transparent"
opacity: 0
flags:Qt.FramelessWindowsHint | Qt.ToolTip
modality: Qt.NonModal
x: Screen.width - content_pop_window.width
y: 100
width: content_loader.width
height: content_loader.height
property alias content_pop_window:content_loader.sourceComponent
MouseArea{
id:content_mouse
anchors.fill: parent
hoverEnabled: true
}
Loader{
id:content_loader
anchors.centerIn:parent
}
Timer{
id:show_timer
interval: 2000
repeat: true
onTriggered:{
hideWindow();
}
}
ParallelAnimation{
id: show_anim
NumberAnimation{
target:pop_window
property: "opacity"
from:pop_window.opacity
to: 1
duration:800
}
NumberAnimation{
target:pop_window
property: "x"
from: Screen.width
to: pop_window.x - content_loader.width
duration:800
}
onStarted:{
pop_window.show()
}
onFinished:{
show_timer.start()
}
}
ParallelAnimation{
id: hide_anim
NumberAnimation{
target:pop_window
property: "opacity"
from:pop_window.opacity
to: 0
duration:800
}
NumberAnimation{
target:pop_window
property: "x"
from: pop_window.x
to: Screen.width
duration:800
}
onFinished:{
show_timer.stop();
pop_window.close();
}
}
function showWindow(){
show_anim.start()
}
function hideWindow(){
show_anim.stop()
hide_anim.start()
}
}
调用:
这里的调用写的其实有点多了,直接在content_pop_window 里面创建控件然后相应信号执行pop.showWindow 就能看到弹窗的效果了
import QtQuick
import QtQuick.Controls 2.5
import QtQuick.Window 2.3
import Qt5Compat.GraphicalEffects
Window{
visible: true
Button{
text:"Pop"
width:100
height:50
anchors.centerIn:parent
onClicked:pop.showWindow()
}
PopWindow{
id:pop
x: get_screen_pixel(1, Screen.width) - get_screen_pixel(0.005, Screen.width)
y: get_screen_pixel(0.13, Screen.height)
content_pop_window:
Rectangle{
id:bk_rectangle
width:200
height:70
radius:10
color: Qt.rgba(0.8,0.8,0.8,0.8)
Image {
id: img
width: 60
height: 60
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
anchors.leftMargin:6
source: "/txwh_icon.jpg"
smooth: true
visible: false
}
Rectangle {
id: img_mask
width: img.width
height: img.height
radius: 10
color: "red"
visible: false
}
OpacityMask {
anchors.fill: img
source: img
maskSource: img_mask
}
Text{
id:music_name
anchors.verticalCenter: parent.verticalCenter
anchors.verticalCenterOffset: -16
anchors.left:img.right
anchors.leftMargin:10
font.pointSize:13
text:qsTr("Music Name")
}
Text{
id:player_name
anchors.verticalCenter: parent.verticalCenter
anchors.verticalCenterOffset: 16
anchors.left:img.right
anchors.leftMargin:10
font.pointSize:11
text:qsTr("Player")
}
MouseArea{
anchors.fill:parent
}
}
}
function get_screen_pixel(percent, sum_pixel){
return percent * sum_pixel
}
}
参考:QML实现桌面右下角弹窗
|