How to display TextField at the bottom of the screen

1.4k Views Asked by At

I want to display a TextField at the bottom of the screen in QML for SailfishOS.

I attempted multiple tries but the TextField is always at the top of the screen.

import QtQuick 2.0
import Sailfish.Silica 1.0

ApplicationWindow {
     id: screen
     anchors.fill: parent
    Item {
        width: parent.width;
        anchors.bottom: screen.bottom
        TextField {
            width: parent.width;
            anchors.bottom: screen.bottom
            id: input
            placeholderText: "URL"
            inputMethodHints: Qt.ImhNoPredictiveText
            validator: RegExpValidator { regExp: /^[a-zA-Z]{3,}$/ }
        }
    }
}
2

There are 2 best solutions below

4
NG_ On BEST ANSWER

Kaymaz, in common, your question is not related to SailfishOS. And you was almost right, but made several errors in your code. You can use this code:

// Its desktop version, and everyone can run it. It will be easy 
// to insert correct includes for SailfishOS
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Window 2.2

ApplicationWindow {
    id: appWindow

    // Explicitly set window size (just for testing on desktop)
    width: 200
    height: 400

    // Item that represents "main application rectangle"
    // it will contain all child items
    Item {
        id: root
        anchors.fill: parent

        TextField {
            id: input
            anchors {
                left: parent.left
                right: parent.right
                bottom: root.bottom
            }
            placeholderText: "URL"
            inputMethodHints: Qt.ImhNoPredictiveText
            validator: RegExpValidator { regExp: /^[a-zA-Z]{3,}$/ }
        }
    }
}

I do not recommend use folibis's approach for several reasons:

  • If you can use anchors in QML -- use it.
  • Avoid unnamed constants (like 30).
  • Such code becomes hard to read (I mean, if it is more than 20 lines).
  • Imagine, that your TextField's height change -- you got need to change y: screen.height - 30. So this kind of code becomes hard to maintain.
  • Do not write code thinking "I can improve this later". Write good code.
3
folibis On

Try this:

ApplicationWindow {
    id: screen
    width: 400
    height: 300

    TextField {
        width: screen.width
        y: screen.height - height
        placeholderText: "URL"
    }
}