QString的arg的思考

2023-03-17 15:11:25 浏览数 (1)

  使用Qt的arg格式化以下字符串:

代码语言:javascript复制
QString marjor = "2";
QString minor = "0";
QString patch = "1";

QString str = QString("Version: v%1.%2.%3, "
                      "major version number is %1, "
                      "minor version number is %2, "
                      "patch version number is %3")
                      .arg(marjor)
                      .arg(minor)
                      .arg(patch);

  我们可以看出上面的%1,%2和%3分别对应marjor,minor和patch,使用起来非常方便。

  QString的arg操作,最多可以使用%1到�的占位符。但%1,%2这类占位符,有一个缺点是不直观,要提前知道%1对应的是什么,%2对应的又是什么,如果占位符太多,会导致非常容易出错。

  由此引出一种想法是,假如%1,%2...这类占位符像python指定名称的占位符多好啊,比如:

代码语言:javascript复制
# python语法
str = "My name is {name}, I'am {age}".format(name = "peter", age = 18)

  查找了相关QString文档,遗憾的是QString的arg方法并不支持上述这种方法。在查看QString官方文档中看到这段话:

代码语言:javascript复制
QString QString::arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
Returns a copy of this string with the lowest numbered place marker replaced by string a, i.e., %1, %2, ..., �.
返回此字符串的副本,将编号最低的位置标记替换为字符串a,即%1,%2,…, % 99。

  既然文档提到替换操作,那么我们可以使用QString的replace操作实现。比如这样:

代码语言:javascript复制
QString str("Version: v%{marjor}.%{minor}.%{patch}, "
            "major version number is %{marjor}, "
            "minor version number is %{minor}, "
            "patch version number is %{patch}");
            
str.replace("%{marjor}", marjor);
str.replace("%{minor}", minor);
str.replace("%{patch}", patch);

  由于replace返回的是自身引用,我们还可以这样操作:

代码语言:javascript复制
str.replace("%{marjor}", marjor) // 返回自己的引用,可以进行链式调用;
   .replace("%{minor}", minor)
   .replace("%{patch}", patch);

  把%去除会更简洁些。

代码语言:javascript复制
QString str("Version: v{marjor}.{minor}.{patch}, "
            "major version number is {marjor}, "
            "minor version number is {minor}, "
            "patch version number is {patch}");

str.replace("{marjor}", marjor)
   .replace("{minor}", minor)
   .replace("{patch}", patch);

0 人点赞