[Qt-qml] how to set text vertical center alignment

Henry Gomersall heng at cantab.net
Fri Jun 17 10:20:36 CEST 2011


On Fri, 2011-06-17 at 13:59 +0800, Miao, Qiankun wrote:
> For example I can select the text “Hello, world” in the blank area
> under the text in the following code. But no space above the text. If
> TextInput could be vertical center alignment, no such issue.
> 
> Any comments are appreciated. 

Here's a rather hacky way of doing it in pure QML. It uses a dummy text
box to handle the selection when the mouse is not over the actual text
box, which then calls suitable methods to perform the selection.
Annoyingly, the text box item doesn't allow text selection when its
transparent, so the hacky method is just to camouflage it (or you could
reduce its opacity to a very small but non-zero value). It may need more
hacking if you want to do more elaborate stuff.

cheers,

Henry

code:
import Qt 4.7

Rectangle {

    id: rectangle

    width: 600

    height: 400
    TextInput {

        id: dummy_textinput
        anchors.fill: parent
        anchors.topMargin: 0        

        horizontalAlignment: TextInput.AlignHCenter

        text: textinput.text
        
        onCursorPositionChanged: {
            if (selectionStart == selectionEnd) {
                textinput.cursorPosition = cursorPosition
            }
        }         

        onSelectionStartChanged: {
            if (selectionStart == cursorPosition){
                textinput.select(selectionEnd, selectionStart)
            } else {
                textinput.select(selectionStart, selectionEnd)
            }
        }
        onSelectionEndChanged: {
            if (selectionStart == cursorPosition){
                textinput.select(selectionEnd, selectionStart)
            } else {
                textinput.select(selectionStart, selectionEnd)
            }
        }
        
        cursorVisible: false
        color: parent.color
        selectedTextColor: color
        selectionColor: color

        selectByMouse: true

    }

    
    TextInput {

        id: textinput

        anchors.fill: parent
        anchors.topMargin: 200        

        horizontalAlignment: TextInput.AlignHCenter

        text: "Hello, World!"

        cursorVisible: dummy_textinput.cursorVisible

        selectByMouse: true

    }

}



More information about the Qt-qml mailing list