2013-02-13 50 views
0

的Windows 7 SP1
MSVS 2010
的Qt 4.8.4
为什么select(QTextCursor :: BlockUnderCursor)包含额外的垃圾字符?

我使用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(); 
} 

回答

1

这不是垃圾。第一个字符包括U + 2029段落分隔符(HTML:
 PSEP)。换句话说,选择块包括起始段落分隔符。第一个块没有启动SEP。因此,如果想单独提取后续块的文本,则需要排除第一个字符。

0

导航值有一个QTextBlock的性质做,以及如何通过块导航以及由BlockUnderCursor确定的内容。该文档提供了一些洞察到这一点:

http://doc.qt.digia.com/main-snapshot/qtextblock.html#details

这里是文档的另一部分似乎对我很有帮助:

http://doc.qt.digia.com/main-snapshot/qtextblockformat.html#details

我还没有跟你发现了什么尝试,但在这里是我的一些想法:

在某些方面,我认为它像在Windows中按下Ctrl + Up或Ctrl + Down在MS Word文档。其中一些可能与您正在使用的行结尾有关。 “\ r \ n”v。“\ n”。我知道有时候“eof”角色很奇怪。某些文件和格式在文件字符结束之前需要换行。

希望有所帮助。