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

时间:2018-07-02 12:23:51

标签: python pyqt iteration qtextedit qtextdocument

使用QTextDocument时,Qt提供迭代器(例如QTextBlock.iterator)在内容之间移动。文档here显示了C ++代码,但是显然++运算符不起作用,PyQt版本似乎没有类似next()的功能。

那么如何使迭代器迭代?

QTextFrame.begin的文档(返回迭代器)的“ STL-style-Iterators”链接断开,但是我找不到在Python中实现的这些细节。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

这似乎可行。

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())

对不起。我不了解QTextFrame。我尝试添加以下内容,但显然没有要迭代的框架。它没有引发任何错误。

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())