Localization and numerals

    There are a lot of articles on Habré, with examples in different languages, on how to correctly process numerals and incline nouns related to them. Let's see how this problem is solved in Qt.

    In a previous article on localization in Qt , the QObject :: tr () function was mentioned and it was even said that placeholders% 1,% 2, etc. can be inserted into a string.

    However, unfortunately, a special placeholder is not mentioned -% n. If you look closely at the signature of the QObject :: tr function
    QString QObject::tr ( const char * sourceText, const char * comment = 0, int n = -1 )
    you can see that she has a third parameter - a certain integer n, what is it?

    Let's take an example from the previous article and simplify it a little, we will show only the number of copied files:
    void FileCopier::showProgress(int done)
    {
    label.setText(tr("%1 files copied.").arg(done));
    }
    As you can see, depending on the condition done == 1, we must write either file or files. When translating into Russian, everything becomes even more complicated - the form becomes 3 (1 file, 2 files, 5 files copied) and the condition becomes more complicated.

    And then the placeholder% n and the third argument of the tr () function come to our aid.
    To make everything right, let's write the showProgress function as follows:
    void FileCopier::showProgress(int done)
    {
    label.setText(tr("%n files copied.", "", done));
    }
    And when translating, in a linguist, we will have the opportunity to set several options for translating this line for different values ​​of% n.

    There will be two options for English - Singular and Plural. Singular will look like this: "% n file copied.", And Plural will look like this: "% n files copied."

    For the Russian three - Singular, Dual and Plural.
    Singular: “Copied% n file.”
    Dual: “Copied% n file.”
    Plural: “Copied% n files.”

    This is where the work of the translator and programmer ends. Qt itself knows for what numerals what form to use in this particular language. When the program is executed, the tr () function, depending on the current locale and the third parameter, will return the desired line.

    If anyone is interested, here are the formulas for some languages ​​used by Qt.

    Also popular now: