2016-03-23 35 views
0

我建立一个QML应用程序,我有一个TextInput组件,如下所示:QML为textInput如何处理的选择和逃生

TextInput { 
       id: editableTextInput 
       text: styleData.value 
       horizontalAlignment: Text.AlignLeft 
       verticalAlignment: Text.AlignVCenter 
       selectionColor: 'darkgray' 
       selectedTextColor: 'white' 
       font.pixelSize: 14 
       font.family: "AvantGarde-Medium" 

       onEditingFinished: { 
        // TO DO: Handle new text 
       } 

       MouseArea { 
        anchors.fill: parent 
        onClicked: { 
         editableTextInput.selectAll() 
        } 
       } 
      } 

目前,它代表的办法就是对文字的用户点击时,它会选择整个文本,然后我可以开始输入,整个文本将被替换,但我希望用户能够进行更精细的控制。首先,用户首先选择全文,然后如果再次点击,则应该将光标放在当前位置。另外,退出键应该基本上恢复旧文本并取消整个操作。

这些是文本输入的标准方式。我想知道是否必须明确编程所有这些,或者是否有办法通过TextInput控件获得此行为。

+2

你必须编写它使用它的键QML模块抓住关键事件和鼠标区域捕捉定制点击。 – Cits

回答

0

基本上,你不需要为此使用MouseArea。钩activeFocus决定何时选择文本(初始点击,activeFocus将成为真),存储旧文本,并在编辑完成后恢复,如果按下了转义。

我认为这可以让你的方式一个很好的一部分,你想要什么:

import QtQuick 2.6 

TextInput { 
    text: "Hello world!" + index 
    font.pixelSize: 24 
    width: 300 
    height: 30 

    // Store the previous text for restoring it if we cancel 
    property string oldText 

    // Lets us know that the user is cancelling the save 
    property bool cancelling 

    Keys.onEscapePressed: { 
     // Cancel the save, and deselect the text input 
     cancelling = true 
     focus = false 
    } 

    onEditingFinished: { 
     if (cancelling) { 
      // When cancelling, restore the old text, and clear state. 
      text = oldText 
      oldText = "" 
      cancelling = false 
     } else { 
      // TO DO: Handle new text 
     } 
    } 

    onActiveFocusChanged: { 
     // When we first gain focus, save the old text and select everything for clearing. 
     if (activeFocus) { 
      oldText = text 
      selectAll() 
     } 
    } 
}