gpt4 book ai didi

python - 如果 QPlainTextEdit 有空文本,则认为它已被修改

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:59 25 4
gpt4 key购买 nike

我正在使用 PyQt 构建一个简单的 IDE,如果加载空文件,则会出现奇怪的错误。下面发布了一个小示例脚本:

#!/usr/bin/env python
import sys
from PyQt4 import QtGui
class TestApp(QtGui.QMainWindow):
def __init__(self, filename=None):
super(TestApp, self).__init__()
self._editor = QtGui.QPlainTextEdit()
self._editor.modificationChanged.connect(self._change_modified)
self.setCentralWidget(self._editor)
self._editor.setPlainText('a')
def _change_modified(self, have_change):
print(have_change)
if __name__ == '__main__':
a = QtGui.QApplication([])
app = TestApp()
app.show()
sys.exit(a.exec_())

正如预期的那样,这显示了一个带有纯文本编辑器的窗口。尽快setPlainText调用方法时,编辑器会发出两个事件: 一 modificationChanged事件与 changes=True ,第二个 changes=False 。有点奇怪,但还好。但是,如果您更改 setPlainText('a')setPlainText('') ,仅发出一个事件,这次是 changes=True 。更糟糕的是,在告诉编辑它没有被 setModified(False) 修改后,它坚持认为已经以某种方式进行了更改。

有谁知道造成此问题的原因以及如何解决此问题?

<小时/>

更新:这似乎是一个错误并且也会影响 QPlainTextEdit.clear() .

下面的解决方法在 QPlainTextEdit 周围放置一个包装器修复clear()setPlainText('') .

#!/usr/bin/env python
import sys
from PyQt4 import QtGui
class TestApp(QtGui.QMainWindow):
def __init__(self, filename=None):
super(TestApp, self).__init__()
self._editor = PlainTextEdit()
self._editor.modificationChanged.connect(self._change_modified)
self.setCentralWidget(self._editor)
self._editor.setPlainText('')
def _change_modified(self, have_change):
print(have_change)
class PlainTextEdit(QtGui.QPlainTextEdit):
def clear(self):
self.selectAll()
cursor = self.textCursor()
cursor.removeSelectedText()
doc = self.document()
doc.clearUndoRedoStacks()
doc.setModified(False)
self.modificationChanged.emit(False)
def setPlainText(self, text):
if text:
super(PlainTextEdit, self).setPlainText(text)
else:
self.clear()
if __name__ == '__main__':
a = QtGui.QApplication([])
app = TestApp()
app.show()
sys.exit(a.exec_())

最佳答案

这是一个 Qt 错误,简单的解决方法是检查是否有空内容(如果指示修改)。

关于python - 如果 QPlainTextEdit 有空文本,则认为它已被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31610351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com