main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
ApplicationWindow {
id: rootWindow
visible: true
width: 640
height: 480
title: qsTr("Hello World")
flags: Qt.Window | Qt.FramelessWindowHint
property point dragStart
property bool dragActive: false
// 引入自定义标题栏部件
TitleBar {
id: titleBar
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
window: rootWindow
}
}
TitleBar.qml
import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Window 2.0
Item {
id: titleBar
height: 40
property Window window
Rectangle {
width: parent.width
height: parent.height
color: "black"
border.color: "red"
}
Text {
id: titleText
text: window.title
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
anchors.leftMargin: 10
color: "white"
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton
property point clickPos
onPressed: {
clickPos = Qt.point(mouse.x, mouse.y)
window.dragStart = Qt.point(mouse.x, mouse.y)
window.dragActive = true
}
onReleased: {
window.dragActive = false
}
onPositionChanged: {
if (window.dragActive) {
var delta = Qt.point(mouse.x - clickPos.x, mouse.y - clickPos.y)
window.x += delta.x
window.y += delta.y
}
}
onDoubleClicked: {
if (window.visibility === Window.Maximized) {
window.visibility = Window.Normal
} else {
window.visibility = Window.Maximized
}
}
}
Button {
id: minimizeBtn
width: 30
height: 30
anchors.right: maximizeBtn.left
anchors.rightMargin: 5
anchors.verticalCenter: parent.verticalCenter
text: "一"
hoverEnabled: true
background: Rectangle {
color: Qt.rgba(0, 0, 0, 0)
Image {
anchors.fill: parent
// source: minimizeBtn.hovered ? (minimizeBtn.pressed ? "qrc:/res/min_pressed.png" : "qrc:/res/min_hover.png") : "qrc:/res/min.png"
}
}
onClicked: {
window.visibility = Window.Minimized
}
}
Button {
id: maximizeBtn
width: 30
height: 30
anchors.right: closeBtn.left
anchors.rightMargin: 5
anchors.verticalCenter: parent.verticalCenter
text: "口"
hoverEnabled: true
background: Rectangle {
color: Qt.rgba(0, 0, 0, 0)
Image {
anchors.fill: parent
// source: maximizeBtn.hovered ? (maximizeBtn.pressed ? "qrc:/res/max_pressed.png" : "qrc:/res/max_hover.png") : "qrc:/res/max.png"
}
}
onClicked: {
if (window.visibility === Window.Maximized) {
window.visibility = Window.Normal
} else {
window.visibility = Window.Maximized
}
}
}
Button {
id: closeBtn
width: 30
height: 30
anchors.right: parent.right
anchors.rightMargin: 5
anchors.verticalCenter: parent.verticalCenter
text: "X"
hoverEnabled: true
background: Rectangle {
color: Qt.rgba(0, 0, 0, 0)
Image {
anchors.fill: parent
// source: closeBtn.hovered ? (closeBtn.pressed ? "qrc:/res/close_pressed.png" : "qrc:/res/close_hover.png") : "qrc:/res/close.png"
}
}
onClicked: {
window.close()
}
}
}