Handle Key Press Event in Qt - Detecting Which Key is Pressed

Summary : This code shows how to handle QKeyEvent and detect which key is pressed on keyboard.
 Qt Version:  4.7.4
//main.cpp file

#include <QApplication>
#include <QMainWindow>
#include "mywindow.h"
int main(int argc, char **argv)
{
	QApplication app(argc, argv);

	MyWindow *window = new MyWindow();    
    
        window->setWindowTitle(QString::fromUtf8("Handling QKeyEvent"));
        window->resize(336, 227);
	
	window->show();
	return app.exec();
}
//mywindow.h File

#ifndef MYWINDOW_H
#define MYWINDOW_H
#include<QMainWindow>
#include<QMessageBox>
#include<QKeyEvent>

class MyWindow: public QMainWindow
{
  Q_OBJECT
  
  public:    
	MyWindow()
	{};
	~ MyWindow(){};
   public :    
	void keyPressEvent(QKeyEvent* e)
	{
	      QMessageBox* box = new QMessageBox();
	      box->setWindowTitle(QString("Hello"));
	      box->setText(QString("You Pressed: ")+ e->text());
	      box->show();
	};
};
#endif
Output :
Handling QKeyEvent in QT


Similar Examples
Handle QKeyEvent Key Release in QT
Detect Multiple Key Press (Key Press Combination) with QKeyEvent Modifiers
Detect First-Time Key Press Event

Examples About Some Qt Classes
QLcdNumberQTimer
QPushButtonQMessageBox
QTabWidgetQtConcurrent
QLabelQList
QKeyEventQSlider
QFontDialogQSpinBox
QTableWidgetQTextBrowser
Qt StylesheetsQCheckBox
QComboBoxQCloseEvent
QProgressBarQProgressDialog
QTreeWidgetQSignalMapper



Recommend This : Bookmark and Share
 
Want any example ? Feel free to tell us:
(Max. 2000 characters)
Please note that we do not guarantee to respond.Thanks.

C++
OpenSceneGraph
Fundamentals
QT
Boost
wxWidgets
Java
Python



Copyright 2011 - 2013 | All Rights Reserved
All trademarks are properties of their respective owners.
Contact| Privacy Policy| About Us