Question

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/

Was it helpful?

Solution

The method you're looking for is called keyPressEvent, not KeyPressEvent.


It seems that your QLineEdit is stealing your KeyPress events. If handling the enter key from the line edit is all you want to do, you could connect the returnPressed signal to self.fun:

self.text.returnPressed.connect(self.fun)  # in PySide

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 keyPressEvent and just use:

self.text.returnPressed.connect(self.fun)
self.button.clicked.connect(self.fun)

What a messy answer this turned out to be :)

OTHER TIPS

You are making the GUI application, right? if yes then printing like that will print in the console. try this...

QtGui.QMessageBox.information(self,"hello","I m here")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top