25

I'm wondering How I can have a string in QML that will be occupied with some arguments? Some thing like this in Qt:

QString str("%1 %2");
str = str.arg("Number").arg(12);//str = "Number 12"
s4eed
  • 7,173
  • 9
  • 67
  • 104

6 Answers6

35

In QML environment, the arg() function already added to the string prototype, so basically you can use the string.arg() in QML just like C++.

There is less documentation about this, but I'm sure it works in Qt 4.7 + QtQuick 1.1

Take at look at the Qt 5 doc : http://qt-project.org/doc/qt-5.0/qtqml/qml-string.html

James Z
  • 12,209
  • 10
  • 24
  • 44
Dickson
  • 1,201
  • 10
  • 19
23

just use :

"foo%1".arg("bar");
TheBootroo
  • 7,408
  • 2
  • 31
  • 43
2

if you want multiple argument replacements:

"foo%1 bar%2".arg("bar").arg("foo");
GO.exe
  • 646
  • 7
  • 13
1
property string str1: "Foo"
property string str2: `${str1}/Bar` // here will "Foo/Bar" as result
magrif
  • 396
  • 4
  • 20
-1

You might be able to do this with a jQuery plugin:

http://docs.jquery.com/Plugins/Validation/jQuery.format

import "jQuery.js" as JQuery

    Page {

        property string labelStub: "hello {0}"

        Label {
            text: JQuery.validator.format(labelStub, "world")
        }
     }
Jace
  • 1,445
  • 9
  • 20
-3

Arguments are totally unnecessary in this example. In JS, we have simple string concatenation which also supports numbers in between, so you can achieve this with a simple

var str = 'Number' + ' ' + 12

If you really want arguments in non-literal strings, you can just replace the %1 with the replacement. QString::arg (with one argument) is nothing more than the following:

function stringArg(str, arg)
{
    for(var i = 1; i <= 9; ++i)
        if(str.indexOf('%'+i) !== -1)
            return str.replace('%'+i, arg);
    return str;
}

So your code becomes:

var str = "%1 %2"
str = stringArg(str, "Number")
str = stringArg(str, 12)

(Note that this function can only handle %1..%9, while QString::arg can handle up to %99. This requires a bit more logic, since %10 is teated as a %1 in my code. So this is not exactly the same as QString::arg, but it will suffice in the most cases. You could also write a stringArg function taking multiple replacement arguments, but for the simplicity I just wrote this one here.)

leemes
  • 44,967
  • 21
  • 135
  • 183