C++ Qt5.10文档中QtQuick中关于键盘焦点的错误?

C++ Qt5.10文档中QtQuick中关于键盘焦点的错误?,c++,qt,qtquick2,qt-quick,C++,Qt,Qtquick2,Qt Quick,我正在阅读Qt文档,学习Qt Quick中的键盘焦点!我运行文档中的代码。但是,结果与文档不同!代码如下 main.qml //Window code that imports MyWidget Rectangle { id: window color: "white"; width: 240; height: 150 Column { anchors.centerIn: parent; spacing: 15 MyWidget { focus: true

我正在阅读Qt文档,学习Qt Quick中的键盘焦点!我运行文档中的代码。但是,结果与文档不同!代码如下

main.qml

//Window code that imports MyWidget
Rectangle {
id: window
color: "white"; width: 240; height: 150

Column {
    anchors.centerIn: parent; spacing: 15

    MyWidget {
        focus: true             //set this MyWidget to receive the focus
        color: "lightblue"
    }
    MyWidget {
        color: "palegreen"
    }
}
MyWidget.qml

Rectangle {
  id: widget
  color: "lightsteelblue"; width: 175; height: 25; radius: 10; antialiasing: 
  true
  Text { id: label; anchors.centerIn: parent}
  focus: true
  Keys.onPressed: {
      if (event.key == Qt.Key_A)
          label.text = 'Key A was pressed'
      else if (event.key == Qt.Key_B)
          label.text = 'Key B was pressed'
      else if (event.key == Qt.Key_C)
          label.text = 'Key C was pressed'
   }
}
pic1是结果表单doc。pic2是我运行的结果,我只是从doc复制代码并运行它

图1

图2

是虫子吗?为什么结果不同

医生说,

我们希望第一个MyWidget对象具有焦点,因此我们将其focus属性设置为true。但是,通过运行代码,我们可以确认第二个小部件接收到焦点

看看MyWidget和窗口代码,问题很明显——有三种类型将focus属性设置为true。两个MyWidget将焦点设置为true,窗口组件也将焦点设置为true。最终,只有一种类型可以有键盘焦点,系统必须决定哪种类型接收焦点。创建第二个MyWidget时,它将接收焦点,因为它是最后一个将其focus属性设置为true的类型

我的问题:

1.为什么结果不同?在我的结果中,第一个小部件接收焦点

2.另外,由于它是最后一个将其焦点属性设置为truein doc的类型,所以它的含义是什么

你可以从这里得到的医生!
我测试了很多次。结果是一样的。也许这些文件已经过时了

当我运行代码时,我会得到与您相同的结果,但这并不重要。这里的要点是要理解,没有FocusScope,您无法控制哪个对象从系统接收焦点,您无法保证QML对象的创建顺序

您是否尝试在第二个MyWidget上设置focus:true?如果您尝试,键盘事件仍将由第一个小部件接收,除非您使用聚焦镜


请注意,您还可以从MyWidget.qml中删除focus:true,甚至不需要手动添加FocusScope,它将由应用程序窗口自动管理。

尝试运行以下修改:

MyWidget {                  //the focus is here
    color: "palegreen"
}
MyWidget {
    focus: true             //set this MyWidget to receive the focus
    color: "lightblue"
}
MyWidget {
    color: "palegreen"
}

有人能帮忙吗?