如何选择QTextEdit段落?

2024-09-29 21:33:24 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,感谢您抽出时间,我需要在cursorPositionChanged()或selectionChanged()上选择一整段正确的段落(从一个点到另一个点),但到目前为止,我还不能使用Python+Qt4来完成,我试过使用光标位置()和cursor.blockUndergroser,QString的函数indexOf()和lastIndexOf()来定位下一个和前一个“点”来计算段段,但总是失败。 希望你能帮助我。 当做。 洛德福德。在


Tags: 函数定位时间cursor段落qt4光标qstring
1条回答
网友
1楼 · 发布于 2024-09-29 21:33:24

从一个点到另一个点的文本片段称为句子,而不是段落。下面是一个工作示例(参见评论):

import sys
from PyQt4 import QtCore, QtGui


class Example(QtGui.QTextEdit):

    def __init__(self):
        super(Example, self).__init__()
        self.cursorPositionChanged.connect(self.updateSelection)
        self.selectionChanged.connect(self.updateSelection)
        self.setPlainText("Lorem ipsum ...")
        self.show()

    def updateSelection(self):
        cursor = self.textCursor() # current position
        cursor.setPosition(cursor.anchor()) # ignore existing selection
        # find a dot before current position
        start_dot = self.document().find(".", cursor, QtGui.QTextDocument.FindBackward)
        if start_dot.isNull(): # if first sentence
            # generate a cursor pointing at document start
            start_dot = QtGui.QTextCursor(self.document())
            start_dot.movePosition(QtGui.QTextCursor.Start)
        # find beginning of the sentence (skip dots and spaces)
        start = self.document().find(QtCore.QRegExp("[^.\\s]"), start_dot)
        if start.isNull(): # just in case
            start = start_dot
        # -1 because the first (found) letter should also be selected
        start_pos = start.position() - 1
        if start_pos < 0: # if first sentence
            start_pos = 0
        #find a dot after current position
        end = self.document().find(".", cursor)
        if end.isNull(): # if last sentence
            # generate a cursor pointing at document end
            end = QtGui.QTextCursor(self.document())
            end.movePosition(QtGui.QTextCursor.End)
        cursor.setPosition(start_pos) #set selection start
        #set selection end
        cursor.setPosition(end.position(), QtGui.QTextCursor.KeepAnchor)
        self.blockSignals(True) # block recursion
        self.setTextCursor(cursor) # set selection
        self.blockSignals(False)


def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

相关问题 更多 >

    热门问题