[英]QML give focus to a Component
我有這段代碼:
//main.qml
Window {
id: root
width: 640
height: 480
visible: true
title: qsTr("Hello World")
objectName: "Window"
onActiveFocusItemChanged: console.log("***** ACTIVE FOCUS:", activeFocusItem, "*****")
StackView {
anchors.fill: parent
initialItem: "qrc:/LoaderPage.qml"
objectName: "StackView"
onCurrentItemChanged: currentItem.forceActiveFocus()
}
}
//LoaderPage.qml
Item {
objectName: "ItemLoaderPage"
// Keys.forwardTo: loader
Loader {
id: loader
anchors.fill: parent
objectName: "Loader"
focus: true
sourceComponent: rect1
}
Component {
id: rect1
Rectangle {
Keys.onReleased: {
if(event.key === Qt.Key_Escape || event.key === Qt.Key_Back)
{
console.log("Esc or back pressed from", objectName)
event.accepted = true
}
}
objectName: "Rectangle"
focus: true
color: "blue"
}
}
}
我試圖將焦點放在 rect1 組件中的 Rectangle 上並捕獲關鍵事件,但是使用此代碼,焦點始終放在 ItemLoaderPage 上,我無法捕獲關鍵事件。 我該如何解決?
我發現在 Qt 中保持鍵盤焦點是一個很大的弱點。文檔使這一切聽起來很簡單,但在實踐中,我總是會遇到甚至不知道焦點在哪里的情況。
我通常求助於手動調用 forceActiveFocus() 而不是依賴 Qt 來自動執行正確的操作。 這是一個脆弱的解決方案,但至少我覺得我可以控制它。
Loader {
sourceComponent: rect1
onLoaded: {
item.forceActiveFocus();
}
}
Loader 和矩形已通過您的屬性請求焦點:
focus: true
如果我對 focus-attribute 的理解正確,你應該嘗試只設置一次焦點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.