2014-12-02 279 views
4

我正在开发qt快速应用程序,我想打开对话框。在这个对话窗口中是TextField,我想在对话框打开后将焦点设置到这个文本框。 此代码没有工作。带聚焦textField的QML对话框

function newFolder() { 
    newFolderDialog.visible = true 
    newFolderDialog.open() 
} 

Dialog { 
    id: newFolderDialog 
    title: "New folder" 
    height: 150 
    width: 300 
    standardButtons: StandardButton.Ok | StandardButton.Cancel 

    Column { 
     anchors.fill: parent 
     Text { 
      text: "Name" 
      height: 40 
     } 
     TextField { 
      id: newFolderInput 
      width: parent.width * 0.75 
      focus: true 
      onFocusChanged: console.log("Focus changed " + focus) 
     } 
    } 

    onVisibilityChanged: { 
     if(visible === true){ 
      newFolderInput.text = "" 
      newFolderInput.focus = true 
     } 

    } 
} 

输出到控制台

QML:重点变成假
QML:重点变成真正
QML:重点变成假

它的样子,不知怎的焦点在我将焦点设置为textField后更改了

+0

这适用于我在Qt 5.5中。重点放在TextField上,控制台中有四行(false,true,false,true)。 – pepan 2016-02-08 10:57:17

回答

5

您不需要n按照写入的顺序执行函数。从功能Dialog的文档open()

向用户显示对话框。它等于相当于将可见设置为true。

鉴于(这不是问题),似乎焦点在对话框和包含的元素之间不断争用。您打开/关闭Dialog越多,评估就越多。我现在无法弄清楚为什么会发生这种情况。但是,您可以通过以下方式轻松解决问题:(1)取消处理程序和(2)重写newFolder()。最后的代码重写:

ApplicationWindow { 
    width: 360 
    height: 300 
    visible: true 

    Button { 
     anchors.centerIn: parent 
     text: "click me!" 
     onClicked: newFolder() 
    } 

    Dialog { 
     id: newFolderDialog 
     title: "New folder" 
     height: 150 
     width: 300 
     standardButtons: StandardButton.Ok | StandardButton.Cancel 
     focus: true // Needed in 5.9+ or this code is NOT going to work!! 

     Column { 
      anchors.fill: parent 
      Text { 
       text: "Name" 
       height: 40 
      } 
      TextField { 
       id: newFolderInput 
       width: parent.width * 0.75 
       focus: true 
       onFocusChanged: console.log("Focus changed " + focus) 
      } 
     } 
    } 

    function newFolder() { 
     newFolderDialog.open() 
     newFolderInput.focus = true 
    } 
} 

这样,你第一次打开对话框,然后将焦点设置到适当Item

+0

你的解决方案没有帮助。它正确显示对话框,但不会将焦点添加到textField – user3412372 2014-12-02 19:32:35

+0

它适用于我,5.3和5.4。我用我的完整测试代码(这是你的代码加一个按钮......)进行编辑。也许有关于你的设置缺少的东西? – BaCaRoZzo 2014-12-02 20:48:52

+1

是的,它的工作!我的坏处是,我写了'newFolderInput.visible = true'而不是'newFolderInput.focus = true'非常感谢! – user3412372 2014-12-02 20:59:36