MenuBar的高度其实受很多东西影响,因为MenuBar的高度默认会自适应其内部包含的组件。
先来看默认情况下的MenuBar和其代码
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
MenuBar {
Menu {
title: qsTr("File")
Action {
text: qsTr("New")
shortcut: "Ctrl+N"
onTriggered: console.log(1)
}
Action {
text: qsTr("Open")
shortcut: "Ctrl+O"
onTriggered: console.log(2)
}
}
Menu {
title: qsTr("File")
Action {
text: qsTr("New")
shortcut: "Ctrl+Shift+N"
onTriggered: console.log(3)
}
Action {
text: qsTr("Open")
shortcut: "Ctrl+Shift+O"
onTriggered: console.log(4)
}
}
}
}
可以看到其实默认的MenuBar有那么一点丑,主要是因为height太大,既然你点进了我这一篇文章,那就说明你已经尝试设置了MenuBar的height发现行不通。那是因为:MenuBar的高度受到delegate这个子组件的制约,而这个子组件又是默认定义的,所以很难排查问题。(其实字体的大小变化也会让MenuBar的高度自动变化)
实践发现delegate的topPadding和bottomPadding不为0,所以我们只需要自定义下delegate的topPadding和bottomPadding这两个属性就行了
MenuBar {
delegate: MenuBarItem {
id: menuBarItem
font.pixelSize: 12
topPadding: 0
bottomPadding: 0
}
// 其它代码不变...
}
运行看看结果:
好看多了….