(C++) How to define a OnKeyPress Event?
February 24, 2017 · View on GitHub
(C++)
How to define a OnKeyPress Event?
How to define a OnKeyPress Event? is a QT FAQ for if you want to respond to key presses/releases.
Project and source code
Operating system: Ubuntu 10.04 LTS Lucid Lynx
IDE: Qt Creator 2.0.0
Project type: Qt4 GUI Application
Libraries used:
- Qt: version 4.7.0 (32 bit)
- View a screenshot of 'CppQtOnKeyPress' (png)
- Download the Qt Creator project 'CppQtOnKeyPress' (zip)
main.cpp
#include <QApplication> #include "dialog.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Dialog w; w.show(); return a.exec(); }
dialog.h
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> struct QKeyEvent; namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); protected: void changeEvent(QEvent *e); private: Ui::Dialog *ui; private slots: void keyPressEvent(QKeyEvent * e); void keyReleaseEvent(QKeyEvent * e); }; //From http://www.richelbilderbeek.nl/CppIntToQtStr.htm QString IntToQtStr(const int i); #endif // DIALOG_H
dialog.cpp
#include <QKeyEvent> #include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); } Dialog::~Dialog() { delete ui; } void Dialog::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void Dialog::keyPressEvent(QKeyEvent * e) { switch (e->type()) { case QEvent::KeyPress: ui->text_edit->appendPlainText("Key pressed: " + IntToQtStr(e->key())); break; default: break; } } void Dialog::keyReleaseEvent(QKeyEvent * e) { switch (e->type()) { case QEvent::KeyRelease: ui->text_edit->appendPlainText("Key released: " + IntToQtStr(e->key())); break; default: break; } } //From http://www.richelbilderbeek.nl/CppIntToQtStr.htm QString IntToQtStr(const int i) { QString s; s.setNum(i); return s; }