3

i am doing some experiments on Keyboard Input in Qt5 and now after I did some research I couldn't find a simple way to execute Code if a specific button is pressed e.g. Button R. Now my Question is which way is the most simple to use the Keyboard Input (real Keyboard, not virtual Keyboard) to do things.

I would really appreciate some help or even examples on this :)

Greetings Lybbo

Lybbo
  • 31
  • 1
  • 1
  • 2

1 Answers1

3

Just override in your class QWidget::keyPressEvent method. You can recieve pressed key from QKeyEvent *event argument using QKeyEvent::key method.

Simple example below:

#include <QWidget>
#include <QKeyEvent>

class MyClass : public QWidget
{
    Q_OBJECT
public:
    explicit MyClass(QWidget *parent = 0):QWidget(parent){}

protected:
     void keyPressEvent(QKeyEvent *event) override
     {
         if(event->key() == Qt::Key_R)
         {
             //Do something when 'R' key is pressed
         }
     }
};

You can find more informations in reference.

Rhathin
  • 1,176
  • 2
  • 14
  • 20