PDA

View Full Version : Key Press Event trouble



morraine
16th August 2008, 01:55
Does any one know how to setup Key press event handeling?

i can make head nor tail of the online docs on this issue and i just want to setup the escape button to trigger a function when pressed viewing the main window.

do i have to add a method to the object of the mainwindow class to catch it or something?

i just can see any examples on this at all (or any that make sense)


your help on this would be much appreciated

aamer4yu
16th August 2008, 08:11
You can subclass the window and override the keyPressEvent.
Or you can install filter on window to get its event...
QWidget::keyPressEvent

QObject::installEventFilter

morraine
16th August 2008, 09:08
sorry but i looked at the docs and i cant make sense of it have yo please got a sample code to subclass the QMainWindow and add a keyPressEvent to it for QT:Key_Escape key
ive tried every thing but i cant get it to work

Thank you

aamer4yu
16th August 2008, 09:31
can we see wat u tried ? it shudne be a long code

morraine
16th August 2008, 09:52
im doing this in python PTQT i have this code for the filter which is both an activity filter to reset a inactivity timer and a filter to react to the Escape key but its not working.





class activityFilter(QObject):

def __init__(self, parent=None):
super(activityFilter, self).__init__(parent)
self.eventaction = turnOffApp()
self.eventexit = MainDisplay()

def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Escape:
self.eventexit.lockNow()
else:
self.eventaction.reset()
return QObject.eventFilter(self, obj, event)




Then at the bottom of the page i call the main Window an put this filter on it




def main():
app = QApplication(sys.argv)
app.setOrganizationName("random.")
app.setOrganizationDomain("random")
app.setApplicationName("random")
app.setWindowIcon(QIcon(":/icon.png"))


filename = os.path.join(os.path.dirname(os.path.dirname(__fil e__)), "dataCache.db")
create = not QFile.exists(filename)

db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(filename)
if not db.open():
QMessageBox.warning(None, "Store Application",
QString("Database Error: %1").arg(db.lastError().text()))
sys.exit(1)
if create:
createDatabaseData()

app.processEvents()
form = MainWindow()
ef = activityFilter()
form.installEventFilter(ef)
form.show()
app.exec_()


main()




the filter calls to other class functions which are definitely working the problem lies in the filter

pshah.mumbai
16th August 2008, 15:36
this this...

8. def eventFilter(self, obj, event):

to

def keyPressEvent(self, event):


http://www.zetcode.com/tutorials/pyqt4/eventsandsignals/

section "Reimplementing event handler"

morraine
18th August 2008, 09:43
Thanks for getting back to me that look slike a good tutorial you have linked there. i will look at that today.

Cheers!