This is my keyPressEvent
def keyPressEvent(self , e):
key = e.key()
if key == QtCore.Qt.Key_Escape:
self.close()
elif key == QtCore.Qt.Key_A:
print 'Im here'
However if I click on A , it doesn’t print. However the window is closing if I click on Escape.Where am I going wrong?
EDIT:
Basically I have a window with a lineedit and a pushbutton. I want to link the button to a function by clicking on Enter, lets say fun. This is my code
import sys
from PyQt4 import QtGui , QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example , self).__init__()
self.window()
def window(self):
self.setWindowTitle('Trial')
self.layout = QtGui.QGridLayout()
self.text = QtGui.QLineEdit()
self.first = QtGui.QPushButton('Button')
self.layout.addWidget(self.text , 0 , 0)
self.layout.addWidget(self.first , 1 , 0)
self.setLayout(self.layout)
self.first.clicked.connect(self.fun)
self.show()
def fun(self):
//do something
def keyPressEvent(self , e):
key = e.key()
if key == QtCore.Qt.Key_Escape:
self.close()
elif key == QtCore.Qt.Key_Enter:
self.fun()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I would add more keys later on. But none of them except Escape are working/
The method you’re looking for is called
keyPressEvent, notKeyPressEvent.It seems that your
QLineEditis stealing yourKeyPressevents. If handling the enter key from the line edit is all you want to do, you could connect thereturnPressedsignal toself.fun:Otherwise, you will have to mess around with event filters. I’ll try posting some code later on.
Your final edit made it clearer. You can safely drop
keyPressEventand just use:What a messy answer this turned out to be 🙂