TextField 改变背景

TextField change background

我有一个自定义按钮,当按下该按钮时,我想将没有文本的 TextFields 的颜色从默认值更改为红色,持续 2 秒,然后弹出一个工具提示,说明您有在继续之前写一些东西。

TextField {
    id: textfield_derivat
    placeholderText: qsTr("Write a comment here...")
    horizontalAlignment: Text.AlignHCenter
}


CustomSelectionButton {
    id: go_button
    x: 378
    y: 342
    text: "Let's go!"
    anchors.rightMargin: 19
    anchors.bottomMargin: 17
    anchors.bottom: parent.bottom
    anchors.right: parent.right
    height: default_button_height - 10
    font.pointSize: default_font_size
    MouseArea {
        anchors.fill: parent
        onClicked: {
            if( check_text_field(textfield_derivat.text) === true )
            {
                /* code here */
            }
            else
            {
                textfield_derivat.text = "Please fill up the text"
                textfield_derivat.background = "red"
            }

我这样做时遇到了这个错误 - 错误:无法将 QString 分配给 QQuickItem*

这是因为 backgroundQQuickItem 而不是 QString。你应该这样写(确保你的初始颜色是你喜欢的):

TextField {
    id: textfield_derivat
    placeholderText: qsTr("Write a comment here...")
    horizontalAlignment: Text.AlignHCenter

    background: Rectangle { 
        id: txt_back
        implicitWidth: 200
        implicitHeight: 40
        color: "white" 
    }
}

...

//textfield_derivat.background = "red"
txt_back.color = "red"

取自:https://doc.qt.io/qt-5/qtquickcontrols2-customize.html#customizing-textfield

请注意,QML 中有 Animation 可用,同时使用 StateTransition,这可能会成为更易读的解决方案