Properly handling a keyPressEvent in a Subclassed PyQT LineEdit

一曲冷凌霜 提交于 2019-12-23 15:12:03

问题


So I have a QLineEdit that I want to catch a shift keypress in.

Here's my code:

class NoteText(QtGui.QLineEdit):
    def __init__(self, parent):
        super (NoteText, self).__init__(parent)

    def keyPressEvent(self, event):
        if (event.modifiers() & QtCore.Qt.ShiftModifier):
            self.shift = True
            print 'Shift!'

As you can guess, I can catch the shift keypress, but then you cannot input text into the LineEdit. I've tried catching keypresses, but I'm not sure quite what to do with them to allow the user to continue to type into the widget.

What am I missing? Thanks!


回答1:


I guess you want the default behavior of the overridden keyPressEvent method you should call the base class implementation, smth like this:

def keyPressEvent(self, event):
    if (event.modifiers() & QtCore.Qt.ShiftModifier):
        self.shift = True
        print 'Shift!'
    # call base class keyPressEvent
    QtGui.QLineEdit.keyPressEvent(self, event)

hope this helps, regards



来源:https://stackoverflow.com/questions/5047558/properly-handling-a-keypressevent-in-a-subclassed-pyqt-lineedit

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