首页 文章

使QML TextField闪烁

提问于
浏览
0

我希望 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)
}

但是,我在 QML 找不到像 QTimer 这样的东西,所以我决定通过动画来做 . 这里 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()
            }
        }
    }

}
}

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

1 回答

  • 2

    试试这个:

    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";
            }
        }
    }
    

相关问题