如何在Qt 6中计算感知字符数?

huangapple go评论80阅读模式
英文:

How to count perceived characters in Qt 6?

问题

我尝试了这里的几个已接受的答案,包括:

  • QTextBoundaryFinder tbf(QTextBoundaryFinder::Grapheme, text);
  • QRegularExpression("\X");
  • text.toUcs4().size();

其中没有一个能正确计算⌨️的可感知字符计数。

英文:

I tried several accepted answers here including:

  • QTextBoundaryFinder tbf(QTextBoundaryFinder::Grapheme, text);
  • QRegularExpression("\X");
  • text.toUcs4().size();

None of them gives a size of one for ⌨️. How can I properly count the perceived character count?

答案1

得分: 1

答案是QTextBoundaryFinder方法。<br/>
我猜想它为什么对你不起作用的原因是你用类似下面的方式初始化了你的文本变量:

QString text = QStringLiteral("⌨️");

如果是这样的话,你的编译器应该会给你一个警告,例如C4566。我建议你在使用下面的解决方案之前,在编译过程中尝试查看消息。


解决方案:正确初始化text的方式是:

QString text = QString::fromStdWString(L"⌨️");

我猜你已经知道了,但以防万一(也为了其他阅读我的答案的人),要小心不要简单地使用text.length()和其他方法。<br/>事实上,这将返回:

  • ⌨: 1 (\u2328)
  • ⌨️: 2 (\u2328 \uFE0F)

我提到这个的原因是,与网站上不同,我的IDE显示键盘字符或其变体形式(在你的问题中使用的带有\uFE0F的形式)是完全相同的。

英文:

The answer is theQTextBoundaryFinder method.<br/>
My guess as to why it does not work for you is that you initialize your text variable with something like:

QString text = QStringLiteral(&quot;⌨️&quot;);

If that is it, your compiler should be giving you a warning, such as C4566. I recommend you try to spot the message during compilation before you use the solution below.


Solution: the correct way to initialize text is:

QString text = QString::fromStdWString(L&quot;⌨️&quot;);

I suppose from your question that you already know it but just in case (and for other people reading my answer), be careful not to simply use text.length() and other methods.<br/>Indeed, that would return:

  • ⌨: 1 (\u2328)
  • ⌨️: 2 (\u2328 \uFE0F)

The reason why I mention it is that, unlike on the website, my IDE shows the very same thing for the keyboard character or its variant form (the one with \uFE0F, used in your question).

huangapple
  • 本文由 发表于 2023年7月24日 15:25:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定