使 QML TextField 闪烁

lnk*_*lnk 1 qt qml

我想TextField在单击按钮时闪烁。使用 QTimer 很容易做到:

void MyLineEdit::buttonClickedSlot{
for(int i=1;i<15;i+=2){
    QTimer::singleShot(100*i, this, SLOT(changeBackgroundColor("QLineEdit{background: red;}")));
    QTimer::singleShot(100*(i+1), this, SLOT((changeBackgroundColor("QLineEdit{background: white;}")));

} 
}
void MyLineEdit::changeBackgroundColor(QString str){
     this->setStyleSheet(str)
}
Run Code Online (Sandbox Code Playgroud)

然而,我没有找到类似的东西,QTimer所以QML我决定通过动画来完成。这QML是代码:

Rectangle{
ColumnLayout{
    anchors.fill: parent
    TextField{
        id: txt
        text: "hello"
        style: TextFieldStyle{
            background:Rectangle {
                id: rect    
                radius: 2
                implicitWidth: 100
                implicitHeight: 24
                border.color: "#333"
                border.width: 1
                color: "white"
            }
        }
    }
    ColorAnimation{
        id: whiteToRed
        target: rect     //reference error: rect is not defined
        properties: "color"
        from: "white"
        to: "red"
        duration: 300

    }

    ColorAnimation{
        id: redToWhite
        target: rect    //reference error: rect is not defined
        properties: "color"
        from: "red"
        to: "white"
        duration: 300

    }


    Button{
        text: "blink"
        onClicked: {
            for(var i=0;i<3;i++){
                whiteToRed.start()
                redToWhite.start()
            }
        }
    }

}
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是存在编译错误:没有定义 rect。我应该如何解决这个问题?

Mee*_*fte 6

尝试这个:

Column{
    anchors.fill: parent

    TextField{
        id: txt
        text: "hello"
        property string color: "white"
        style: TextFieldStyle{
            background: Rectangle {
                id: rect
                radius: 2
                implicitWidth: 100
                implicitHeight: 24
                border.color: "#333"
                border.width: 1
                color: txt.color
                Behavior on color {
                    SequentialAnimation {
                        loops: 3
                        ColorAnimation { from: "white"; to: "red"; duration: 300 }
                        ColorAnimation { from: "red"; to: "white";  duration: 300 }
                    }
                }
            }
        }
    }
    Button{
        text: "blink"
        onClicked: {
            txt.color = "red";
            txt.color = "white";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)