QML对话框中的聚焦textField

10

我正在开发Qt快速应用程序,我想打开对话框。在这个对话框窗口中有一个TextField,我想在dialog打开后将焦点设置到这个textField上。 这段代码不起作用。

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: 焦点变为 false
qml: 焦点变为 true
qml: 焦点变为 false

看起来,在我将焦点设置到 textField 后,焦点发生了某种变化。


这在Qt 5.5中对我有效。焦点转移到TextField,并且控制台中有四行(false,true,false,true)。 - pepan
2个回答

7
您不需要按照现有的函数来实现命令。从`Dialog`的文档中可以看出,对于函数`open()`:
显示对话框给用户。它等价于将"visible"设置为真。
尽管这并不是问题所在,但似乎焦点在对话框和包含元素之间不断争夺。您打开/关闭`Dialog`次数越多,就会发生越多的评估。我现在无法弄清楚为什么会这样。但是,您可以通过两个步骤轻松解决此问题:(1) 摆脱`onVisibilityChanged`处理程序和(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


你的解决方案没有帮助。它可以正确显示对话框,但没有将焦点添加到文本字段。 - user3412372
它在我的5.3和5.4版本上运行良好。我已经编辑了我的完整测试代码(包括您的代码加一个按钮...)。也许是您的设置有些缺失? - BaCaRoZzo
1
是的,它可以工作!我的错误是我写成了 newFolderInput.visible = true 而不是 newFolderInput.focus = true。非常感谢你! - user3412372
2
QT 5.9 及以上版本中,只有在对话框初始化时将 focus 设置为 true 才能使上述解决方案生效。Dialog{focus : true} - pra7
@pra7 我猜他们解决了对话框内的某种 bug?为了支持 QC2 和平台实验室控件,它们或多或少已经停止使用。自从上次使用对话框库以来已经很长时间了。谢谢你指出了这个问题,我会加上那行代码的。 :) - BaCaRoZzo

3

在打开对话框后,我不得不使用forceActiveFocus()方法。

onClicked: {
    dialog.open()
    input.forceActiveFocus()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接