如果QpentedEdit函数涉及到最后一行,则导致故障

2024-09-24 22:24:49 发布

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

我正在开发一个源代码编辑器,它应该具有智能的缩进/删除行为。然而,我的断言方法似乎造成了分割错误。如果有人能找出原因我会很高兴的。在

下面是一个最小的例子:

#!/usr/bin/env python
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtGui
from PyQt4.QtCore import Qt
class Editor(QtGui.QPlainTextEdit):
    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Backtab:
            cursor = self.textCursor()
            start, end = cursor.selectionStart(), cursor.selectionEnd()
            cursor.beginEditBlock()
            b = self.document().findBlock(start)
            while b.isValid() and b.position() <= end:
                t = b.text()
                p1 = b.position()
                p2 = p1 + min(4, len(t) - len(t.lstrip()))
                cursor.setPosition(p1)
                cursor.setPosition(p2, QtGui.QTextCursor.KeepAnchor)
                cursor.removeSelectedText()
                b = b.next()
            cursor.endEditBlock()
        else:
            super(Editor, self).keyPressEvent(event)
class Window(QtGui.QMainWindow):
    """
    New GUI for editing ``.mmt`` files.
    """
    def __init__(self, filename=None):
        super(Window, self).__init__()
        self.e = Editor()
        self.e.setPlainText('Line 1\n    Line 2\n    Line 3')
        self.setCentralWidget(self.e)
        self.e.setFocus()
if __name__ == '__main__':
    a = QtGui.QApplication([])
    w = Window()
    w.show()
    a.exec_()

要重新创建,请选择从第二行开始到第三行结束,然后按Shift+Tab到dedent,End触发segfault。在

平台:

  • 在Fedora(linux)上运行
  • Python 2.7.8(默认值,2014年11月10日,08:19:18)[GCC 4.9.2 20141101(Red Hat 4.9.2-1)]
  • PyQt 4.8.6(但它也发生在PySide中)

更新:

谢谢


Tags: keyfromimportselfevent错误linewindow
1条回答
网友
1楼 · 发布于 2024-09-24 22:24:49

这似乎是Qt中的一个bug:

https://bugreports.qt.io/browse/QTBUG-30051

显然是从QTextCursor.beginEditBlock()导致最后一个块的布局中断,在我的例子中,这导致了一个segfault。

解决方法可能是将删除代码重写为单个操作(在删除后确定文本,删除所有选定行,替换为新文本)

如果有人知道更好的解决办法,请告诉我!

相关问题 更多 >