为什么select(QTextCursor::BlockUnderCursor)包含额外的垃圾字符
Why does select(QTextCursor::BlockUnderCursor) include an extra junk character?
Windows 7 SP1
MSVS 2010
问题4.8.4
我正在使用QTextCursor
来获取每个块的文本。我使用select(QTextCursor::BlockUnderCursor)
获取文本,然后使用movePosition(QTextCursor::NextBlock)
转到下一个块。但是当我再次select(QTextCursor::BlockUnderCursor)
时,我在QString
中得到了一个额外的垃圾字符,并且锚点已经移动到了前一个块的末尾。
将其用于text.txt:
A
B
此代码的注释遍历问题并提出以下问题:
#include <QTGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow* window = new QMainWindow;
QTextEdit* editor = new QTextEdit(window);
QTextDocument* document = new QTextDocument(window);
editor->setDocument(document);
QFile file("test.txt");
if (file.open(QFile::ReadOnly | QFile::Text))
editor->setPlainText(file.readAll());
QTextBlock block = document->begin();
QTextCursor* cursor = new QTextCursor(document);
int pos = cursor->position(); // = 0
int anchor = cursor->anchor(); // = 0
cursor->select(QTextCursor::BlockUnderCursor);
pos = cursor->position(); // = 1
anchor = cursor->anchor(); // = 0
QString text = cursor->selectedText(); // = "A"
int size = text.size(); // = 1
cursor->movePosition(QTextCursor::NextBlock);
pos = cursor->position(); // = 2
anchor = cursor->anchor(); // = 2
cursor->select(QTextCursor::BlockUnderCursor);
pos = cursor->position(); // = 3
anchor = cursor->anchor(); // = 1 Why not 2?
text = cursor->selectedText(); // "B" in debugger
// but text.at(0) = junk & test.at(1) = "B"
size = text.size(); // = 2 Why? Why not 1?
return app.exec();
}
它不是垃圾。第一个字符包括U+2029段落分隔符(HTML: ;PSEP)。换句话说,选择块包括起始段落分隔符。第一个块没有起始SEP。因此,如果要单独提取后续块的文本,则需要排除第一个字符。
导航值与QTextBlock
的性质有关,以及如何按块导航以及BlockUnderCursor
确定什么。文档对此有一些见解:
http://doc.qt.digia.com/main-snapshot/qtextblock.html#details
这是文档的另一部分,对我来说似乎很有帮助:
http://doc.qt.digia.com/main-snapshot/qtextblockformat.html#details
我还没有对你的发现进行实验,但以下是我对它的一些想法:
在某些方面,我认为这就像在MS Word文档中按Windows中的Ctrl+Up或Ctrl+Down。其中一些可能与您使用的行尾有关。"\r\n"v."\n"。我知道有时候"eof"这个角色很奇怪。某些文档和格式要求在文件字符末尾之前添加一行新行。
希望能有所帮助。
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 无法将字符数组转换为包含 utf-8 字符的字符串
- 如何从 QString 中包含的十六进制值中获取 ASCII 字符?
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 如何制作一个只包含字符的简单加载屏幕
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何比较文件中包含的下一个字符
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何获取包含 NULL 字符的外壳代码字符串的长度
- 如果字符串向量包含字符'p',如何检查 c++
- C++ 检查 UTF8 字符串包含指定的字符
- 在 Windows 上,stat 和 GetFileAttributes 对于包含奇怪字符的路径失败
- 无法转换 .CATPart 文件.错误:输入文件路径似乎包含不支持的字符
- 字符串只包含有效的字符?
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 当字符包含表情符号时如何比较字符?
- cout 打印的字符 [] 包含的字符数超过设置长度