QML TextEdit中的占位文本

11
我正在寻找一种方法来显示文本提示,以告知用户期望的输入。以Google搜索栏为例:

enter image description here

这是否有我所缺失的属性,还是需要通过编写脚本来实现?
3个回答

24

在Qt Quick输入项上不存在该属性。您可以在此处投票支持该功能。

同时,您可以使用来自Qt Quick Controls 2的 TextArea

如果您更愿意使用纯Qt Quick,则可以类似于控件所做的方式,在字段上方添加 Text 项:

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    width: 300
    height: 300
    visible: true

    TextEdit {
        id: textEdit
        width: 200
        height: 50

        property string placeholderText: "Enter text here..."

        Text {
            text: textEdit.placeholderText
            color: "#aaa"
            visible: !textEdit.text
        }
    }
}

2
Qt Quick Controls 1 中的 TextField 也可以实现这个功能。 - GrecKo

5

虽然这个问题有点老,但我发现在Android构建中还有另一个需要解决的问题。 由于Android只在你按虚拟键盘上的“确认”按钮后才发送文本编辑信号,因此占位符仍然存在。为了避免这种情况,我建议:

TextEdit {
    id: textEdit
    width: 200
    height: 50

    property string placeholderText: "Enter text here..."

    Text {
        text: textEdit.placeholderText
        color: "#aaa"
        visible: !textEdit.text && !textEdit.activeFocus // <----------- ;-)
    }
}

2
如果您想要单行输入,为什么不使用TextField呢?

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