2014-12-01 104 views
0

單擊按鈕時,我想要TextField閃爍。它容易做到QTimer:使QML TextField閃爍

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) 
} 

但是,我沒有發現任何類似QTimerQML所以我決定通過動畫來做到這一點。這裏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() 
      } 
     } 
    } 

} 
} 

這裏的問題是,有編譯錯誤:不定義的矩形。我應該如何解決這個問題?

回答

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