Transparently get backspace event in PyQt

萝らか妹 提交于 2019-12-20 03:41:27

问题


I want to detect when backspace is pressed in a QPlainTextEdit widget.

I have the following code:

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Backspace:
            print("Backspace pressed")

(in a class inherited from QPlainTextEdit)

The problem is that now pressing backspace (or any other character key) does not insert the character into the text box. I could check for every key and do it that way, however, especially with large files, removing the last character could be inefficient, slow and result in messy code.

Is there a better way of doing this?


回答1:


The keyPressEvent method of QPlainTextEdit already has a certain behavior that among other things is to add text, but when you overwrite it you are eliminating it, so the solution is to call the implementation of the parent not to eliminate that behavior

from PyQt5 import QtCore, QtWidgets

class PlainTextEdit(QtWidgets.QPlainTextEdit):
    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Backspace:
            print("Backspace pressed")
        super(PlainTextEdit, self).keyPressEvent(event)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = PlainTextEdit()
    w.show()
    sys.exit(app.exec_())


来源:https://stackoverflow.com/questions/54846450/transparently-get-backspace-event-in-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!