Nominate our 2022 Qt Champions!

Ignore unused args in QString::arg

  • Hi,
    I have have a QString which will be set by the user and i want to replace some placeholders in the string.
    At the moment i try to replace the placeholders with the arg function, but it gives me warnings if the user does not use all placeholders that i replace.

    My code looks like this.

    QString str = getUserString();
    str = str.arg(getUsername(), getGroup(), getDate(),);

    If the function getUserString returns something like hello-%1-%2-%3 or %3-%2-hello-%1 it works, but if the string contains only two or less placeholders (for example hello-%1-%2 or only hello), i get a warning that arguments are missing.

    How can i ignore unused args?
    Or is there a better way to do this?

  • Although the idea looks good, it might not have the desired behaviour if I understand it correctly.
    So it seems like you want:
    %1 = User Name
    %2 = Group
    %3= Date

    That would work correctly for your example: hello-%1-%2
    But not at all for the following: hello-%2-%3
    Because if you look at the docs on the QString::arg() function you should be aware that the function does not actually care what the value is, it replaces the lowest number with the first argument. Thus if the lowest number is %2 it will replace it with getUsername().

    I suggest (actually what I do and it seems like QtCreator as well) is to define your own variables with some marker, like for instance:

    • %{USER}
    • %{GROUP}
    • %{DATE}

    Then inform the user to use those variables in his input string, for example: hello-%{USER}-%{DATE}
    Then use code to replace each one individually:

    QString str = getUserString();
    str.replace("%{USER}", getUsername());
    str.replace("%{GROUP}", getGroup());
    str.replace("%{DATE}", getDate());

    Another benefit of this is that a user can use the same variable more than once: hello-%{USER}-%{DATE}-%{DATE}

    Edit: Removed str = replace(...) from the example since I see QString::replace() modifies the existing string in place.

  • Thanks, i think i will do it so :)

Log in to reply