《QDebug 2025年3月》
一、Qt Widgets 问题交流
1.
二、Qt Quick 问题交流
1.MenuItem设置enable:false后没法更新hover样式
菜单有时候需要禁用某些选项,使之不可点击,但设置enable:false后就不会更新hover或者highlighted等状态了。可以保留enable:true,自定义过滤hover和点击事件,比如放一个MouseArea在上面拦截点击事件,同时过滤MenuItem的快捷键点击事件。
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15
// 菜单
Menu {
id: control
property bool clickable: true
implicitWidth: 100
// 作为二级菜单,不可点击高度设置成0就不会展开了
implicitHeight: clickable ? contentHeight : 0
margins: 0
bottomInset: 0
topInset: 0
leftInset: 0
rightInset: 0
padding: 1
delegate: MyMenuItem {}
contentItem: ListView {
implicitHeight: contentHeight
model: control.contentModel
interactive: Window.window ? contentHeight > Window.window.height : false
clip: true
currentIndex: control.currentIndex
ScrollIndicator.vertical: ScrollIndicator {}
}
background: Rectangle {
border.color: "black"
}
}
import QtQuick 2.15
import QtQuick.Controls 2.15
// 菜单项
MenuItem {
id: control
// 有子菜单就用子菜单的属性值
property bool clickable: subMenu ? subMenu.clickable : true
implicitWidth: 100
implicitHeight: 30
// 屏蔽快捷键点击
Keys.onPressed: event.accepted = acceptKeyClick(event.key)
Keys.onReleased: event.accepted = acceptKeyClick(event.key)
function acceptKeyClick(key) {
return !clickable && (key === Qt.Key_Space || key === Qt.Key_Return || key === Qt.Key_Enter)
}
contentItem: Text {
readonly property real arrowPadding: (control.subMenu && control.arrow ? control.arrow.width: 0)
readonly property real indicatorPadding: (control.indicator && control.indicator.visible ? control.indicator.width: 0)
leftPadding: indicatorPadding
rightPadding: arrowPadding
text: control.text
color: enabled && clickable ? "red" : "gray"
}
background: Rectangle {
color: highlighted ? "orange" : "white"
}
// 用MouseArea挡住就能保留hover状态且不可点击了
MouseArea {
anchors.fill: parent
hoverEnabled: false
visible: !clickable
}
}
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
width: 640
height: 480
visible: true
title: qsTr("GongJianBo")
MyMenu {
id: ctx_menu
MyMenuItem {
text: "A"
}
MyMenuItem {
text: "B"
// 自定义不可点击时也能处理hover/highlighted样式
clickable: false
}
MyMenuItem {
text: "C"
// 设置enabled:false后不会更新hover/highlighted状态
enabled: false
}
MenuSeparator {}
MyMenu {
title: "A"
MyMenuItem {
text: "A"
}
MyMenuItem {
text: "B"
}
}
MyMenu {
title: "B"
clickable: false
MyMenuItem {
text: "A"
}
MyMenuItem {
text: "B"
}
}
MyMenu {
title: "C"
enabled: false
MyMenuItem {
text: "A"
}
MyMenuItem {
text: "B"
}
}
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.RightButton
onClicked: {
ctx_menu.x = mouseX
ctx_menu.y = mouseY
ctx_menu.open()
}
}
}