英文:
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("⌨️");
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"⌨️");
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论