【问题标题】:How to reset a bulleted list to normal text and back in QTextEdit如何将项目符号列表重置为普通文本并返回 QTextEdit
【发布时间】:2021-12-17 02:42:54
【问题描述】:

我正在尝试将所选行设置为项目符号并返回,这里我将缩进设置为 0,它会破坏项目符号,但 list 属性仍然为 true,因此此代码不会将同一行设置回项目符号再次列表,如何清除底层列表格式,或者最好的方法是什么?

    def bullet_list(self):
    cursor = self.textEdit.textCursor()
    list = cursor.currentList()
    if list:
        listfmt = cursor.currentList().format()
        listfmt.setIndent(0)
        cursor.createList(listfmt)
        self.textEdit.setTextCursor(cursor)
        self.textEdit.setFocus()

    else:
        listFormat = QTextListFormat()
        style = QTextListFormat.Style.ListDisc
        listFormat.setStyle(style)
        cursor.createList(listFormat)
        self.textEdit.setTextCursor(cursor)
        self.textEdit.setFocus()

【问题讨论】:

    标签: python qtextedit pyqt6


    【解决方案1】:

    项目必须从列表中删除,您也不应该再次使用createList

        def bullet_list(self):
            cursor = self.textEdit.textCursor()
            textList = cursor.currentList()
            if textList:
                start = cursor.selectionStart()
                end = cursor.selectionEnd()
                removed = 0
                for i in range(textList.count()):
                    item = textList.item(i - removed)
                    if (item.position() <= end and
                        item.position() + item.length() > start):
                            textList.remove(item)
                            blockCursor = QTextCursor(item)
                            blockFormat = blockCursor.blockFormat()
                            blockFormat.setIndent(0)
                            blockCursor.mergeBlockFormat(blockFormat)
                            removed += 1
                self.textEdit.setTextCursor(cursor)
                self.textEdit.setFocus()
            else:
                listFormat = QTextListFormat()
                style = QTextListFormat.ListDisc
                listFormat.setStyle(style)
                cursor.createList(listFormat)
                self.textEdit.setTextCursor(cursor)
                self.textEdit.setFocus()
    

    注意:list 是 Python 内置的,将其分配给其他任何东西都被认为是不好的做法。

    【讨论】:

    • @JackZero 请注意,我已经更新了答案,因此只有选择中的列表项才会被删除。
    猜你喜欢
    • 2022-01-03
    • 2010-11-05
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2019-12-02
    • 2012-12-23
    相关资源
    最近更新 更多