1.思路
自定义窗体主要有标题栏和内容框组成,于是我们设计两个组件分别为QCustomTitleBar和QCustomWindow
2.QCustomTitleBar.qml
用Row定位器放置常用的三个按钮(其实是四个,最大化和正常模式都是一个按钮)。
借用上文中的自定义button我们直接上代码
import QtQuick 2.0
Rectangle {
property bool isMaxed: false//用于判断当前是最大化还是正常模式
color: "green"
Row{
id: controlButtons
height: 20
anchors.verticalCenter: parent.verticalCenter
anchors.right: parent.right
anchors.rightMargin: 12
spacing: 10
//其中view是主界面的id
TImgTextBtn{
id:min_button
width: 20
height: 20
currentStyle:TImgTextBtn.Style.CircleButton
text:""
onClicked: {
view.showMinimized()
}
}
TImgTextBtn{
id:max_button
width: 20
height: 20
currentStyle:TImgTextBtn.Style.CircleButton
text:""
onClicked: {
view.showMaximized()
isMaxed = true
}
visible: !isMaxed
}
TImgTextBtn{
id:normal_button
width: 20
height: 20
visible: isMaxed
currentStyle:TImgTextBtn.Style.CircleButton
text:""
onClicked: {
view.showNormal()
isMaxed = false
}
}
TImgTextBtn{
id:closing_button
width: 20
height: 20
currentStyle:TImgTextBtn.Style.CircleButton
text:""
onClicked: {
view.close()
}
}
}
}
3.QCustomWindow.qml
这个较为简单主要写了个鼠标操作类,测试效果
import QtQuick 2.0
import QtQuick.Controls 2.0
Rectangle {
Rectangle {
x: 200
y: 200
anchors.fill: parent
color: "#5088E0"
//实例化一个MoveArea
QMouseArea {
//指定control为parent。其实默认就是parent,写出来示意一下
operateControl: parent
anchors.fill: parent
enableStatus: true
}
}
}
4.QMouseArea.qml
鼠标测试可用于所有组件,我们可以在这个qml中设置各种事件,本例子主要是改变鼠标样式和拖动功能,具体效果自行测试
import QtQuick 2.0
MouseArea {
id:mouse_area
//定义按下鼠标终点位置
property real endX:0
property real endY:0
property bool enableStatus:false //是否启用拖动
property var operateControl:parent //操作控件对象
hoverEnabled: true
//按下事件记录鼠标位置
onPressed: {
endX=mouseX
endY=mouseY
}
//鼠标进入当前区域事件
onContainsMouseChanged: {
if(containsMouse)
{
cursorShape=Qt.SizeAllCursor
}
else
{
cursorShape=Qt.ArrowCursor
}
}
//鼠标移动事件
onPositionChanged: {
if(enableStatus&&operateControl&&pressed)
{
//作用的控件平移鼠标拖动的距离
operateControl.x+=mouseX-endX
operateControl.y+=mouseY-endY
}
}
}
5.main.aml
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
id:view
visible: true
width: 640
height: 480
title: qsTr("Hello World")
flags:Qt.FramelessWindowHint
Column{
anchors.fill: parent
spacing:0//设置组件之间的距离
QCustomTitleBar{
width: parent.width
height: 20
}
QCustomWindow{
id:main_window
width: parent.width
height: parent.height-20
}
}
}
6.效果