Gaël Porté
Gaël Porté

Reputation: 13

Qt / QML - Choose how many characters to be displayed in a Text item

I would like to display only the two first characters of a word in a Text item. For example, I have a list of words (FRENCH, ENGLISH, ITALIAN) and I would like to display only (FR, EN, IT).

If I elide the text, I will always get three dots (...) at the end and I don't want that.

Any ideas ?

Thanks in advance

Upvotes: 1

Views: 6428

Answers (2)

Miika Pirttilä
Miika Pirttilä

Reputation: 165

Do remember that the first letters in country names and the corresponding ISO standard 2- or 3-letter country codes are a different thing. For example, the 2-letter code for Andorra is AD. (https://en.wikipedia.org/wiki/ISO_3166-2) -- So, if you are trying to achieve country ISO standard country coding, you should simply make a list of objects, which have the properties name, isoCode2, and so on, as required, for example:

property var myArrayOfCountries: [

{ "name" : "Andorra", "isoCode2" : "AD" },
{ "name" : "United Arab Emirates", "isoCode2" : "AE" },
... 

]

I would probably try to get these from some web service, if available, as the creation and maintenance of such list could be a pain.

...That said, if you simply need to get the first two letters from a string in QML Javascript, I would simply use

text: myString.substring(0, 2)

or perhaps in your case, I presume:

text: myArrayOfStrings[someIndex].substring(0, 2)


Ps., with the object list approach you would use:

text: myArrayOfCountries[someIndex]["isoCode2"]

of course.

Upvotes: 0

Tarod
Tarod

Reputation: 7170

You could set clip to true but then you would need to play with the width.

So I think the best option is to implement a little function in JavaScript to get only the first two letters.

Example:

main.qml

import QtQuick 2.5
import QtQuick.Window 2.2
import "myscript.js" as MyFunctions

Window {
    visible: true

    // You need to play with the width
    Text {
        width: 13
        text: "FRENCH"
        clip: true
    }

    // OK. width is not necessary
    Text {
        y: 60
        text: MyFunctions.substring("FRENCH")
    }

    // We don't want this behaviour
    Text {
        y: 30
        width: 25
        text: "FRENCH"
        elide: Text.ElideRight
    }
}

myscript.js

function substring(str) {
    return str.substring(0, 2);
}

Upvotes: 1

Related Questions