Windows 7 SP1
MSVS 2010
Qt 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();
}发布于 2013-02-14 08:02:20
这不是垃圾。第一个字符包括U+2029段落分隔符(HTML: PSEP)。换句话说,选择块包括开始段落分隔符。第一个块没有起始SEP。因此,如果想要仅提取后续块的文本,则需要排除第一个字符。
发布于 2013-02-14 06:54:19
导航值与QTextBlock的性质、如何按块导航以及BlockUnderCursor确定的内容有关。文档对此提供了一些见解:
http://doc.qt.digia.com/main-snapshot/qtextblock.html#details
以下是文档中对我似乎有帮助的另一部分:
http://doc.qt.digia.com/main-snapshot/qtextblockformat.html#details
我没有用你发现的东西做实验,但这里是我对它的一些想法:
在某些方面,我认为这就像是在微软的Word文档中按Ctrl+Up或Ctrl+Down。其中一些可能与您正在使用的行尾有关。"\r\n“v. "\n”。我知道有时候和"eof“这个角色一起工作是很奇怪的。某些文档和格式需要在文件字符结尾之前换行。
希望这能有所帮助。
https://stackoverflow.com/questions/14864424
复制相似问题