的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();
}