我有一个包含具有多个页面的 StackView 的主页:主菜单,param1Page,param2Page,....
如果激活的项目不是“主菜单”,我想在主页显示主页按钮
Item
{
anchors.fill: parent
StackView
{
id: stackView
initialItem: mainmenuPage
anchors.fill: parent
}
Component
{
id : mainmenuPage
ColumnLayout
{
id : mainmenuColumnLayout
TitleText
{
text: qsTr("Main menu")
Layout.preferredHeight: 50
}
GridView
{
id: grid2
Layout.fillWidth: true
Layout.fillHeight: true
cellWidth: parent.width / 4
cellHeight: 150
Layout.alignment: Qt.AlignCenter
interactive: false
focus: true
model: model
delegate: Item
{
width: grid2.cellWidth;
height: grid2.cellHeight
UserButton
{
picto: symbol
text: title
enabled: isEnabled
font.family: Fonts.icons
height: 120
width: 140
pixelSize: textSize
onClicked: model.goToSettingsItem(type)
}
}
}
}
}
Component
{
id : param1Page
Loader
{
id: param1Loader
anchors.fill: parent
source: "Param1.qml"
}
}
Component
{
id : param2Page
Loader
{
id: param1Loader
anchors.fill: parent
source: "Param2.qml"
}
}
...
}
我使用属性
currentItem
(代表StackView中当前可见的项目)
定制按钮:
PushButton
{
visible: stackView.currentItem !== mainmenuPage
Layout.alignment: Qt.AlignLeft
font.family: Fonts.icons
text: "\uF015" //Home
font.pixelSize: 24
onClicked: {
model.goToMainMenu()
}
}
问题:即使当前Item是mainmenuPage,按钮仍然显示
我尝试调试
console.log("Current item:", stackView.currentItem) // Current item: QQuickColumnLayout(0x5c115150)
我推断 currentItem 包含组件的内容。
我想检查当前项目是什么并进行比较
stack.currentItem !== mainmenuPage
。
Component
实际上并不是这样工作的 - 它们更像是由其他小部件实例化的类定义。因此,mainmenuPage
本身不是一个实例,它的内容/子元素是由 StackView 实例化的。因此, mainmenuPage
及其子级可以有多个实例,因此 id 的作用域仅在 Component
内部,而无法在其外部工作。
作为解决方法,我建议您在
objectName
的内容中添加 Component
以进行比较。这是一个独立的示例:
StackView {
id: stack
anchors.fill: parent
initialItem: mainmenuPage
}
Text {
text: "Visibility Test"
y: 30
visible: stack.currentItem.objectName == 'mainmenuPageNAME'
}
Component {
id : mainmenuPage
Text {
id: innerText
text: "Stack Component"
objectName: 'mainmenuPageNAME'
}
}
可以看到,可见性测试成功通过了objectName对比测试,如图:
当然,使用这种方法时还有其他考虑因素,例如是否要实例化
mainmenuPage
的多个实例以及 objectName 是否必须是唯一的。虽然我猜这不是问题。