QTextBlock 或 QTextFrame 迭代器如何在 PyQt 中工作

How do QTextBlock or QTextFrame iterators work in PyQt

在使用 QTextDocument 时,Qt 提供了迭代器(例如 QTextBlock.iterator)来遍历内容。文档 here 显示了 C++ 代码,但显然 ++ 运算符不起作用,而且 PyQt 版本似乎没有任何类似于 next() 函数的东西。

那么如何让迭代器迭代呢?

QTextFrame.begin(returns 迭代器)的文档有一个损坏的 link 到 "STL-style-Iterators",但我找不到这些正在实施的任何细节在 Python.

这似乎有效。

textEdit = QtWidgets.QTextEdit()
for i in range(10):
    textEdit.append("Paragraph %i" % i)
doc = textEdit.document()
for blockIndex in range(doc.blockCount()):
    block = doc.findBlockByNumber(blockIndex)
    print(block.text())

对不起。我不知道 QTextFrames。我尝试添加以下内容,但显然没有要迭代的框架。不过它没有抛出任何错误。

rootFrame = doc.rootFrame()
for frame in rootFrame.childFrames():
    cursor = frame.lastCursorPosition()
    print("I don't know what frames are for, but the cursor is at %i" % cursor.positionInBlock())

documentation表明在PyQt中,迭代器对象支持__iadd____isub__。这允许您使用,例如it += 1 而不是 ++it.

这是一个小演示:

# from PyQt5.QtWidgets import QApplication, QTextEdit
from PyQt4.QtGui import QApplication, QTextEdit

app = QApplication(['test'])

edit = QTextEdit()
edit.setText('one<b>two</b>three<br>')

it = edit.document().firstBlock().begin()
while not it.atEnd():
    fragment = it.fragment()
    if fragment.isValid():
        print(fragment.text())
    it += 1

输出:

one
two
three