Capture keystrokes with QT and C ++

0

I'm trying to make an application with QT that I get the keys but although it works many times certain keys on my computer does not take them for example I write Hello how are you and I put Hoa coo these.

The code with which I capture the keys is check them and the other is to add as a string to a file:

if(num>=32)
{
    log.open(QFile::Append);
    cadenaa.append(num);
    log.write(cadenaa);
    cadenaa.clear();
    log.close();
}

if(num==13){
    log.open(QFile::Append);
    log.write("\n");
    log.close();
}

short comprobarTeclas()
{
    short i = 0;
    for(i = 0; i < 255; i++){
        if(GetAsyncKeyState(i) == -32767)
            return i;
    }
    return 0;
}

Example of a mainwindow form in qt:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
    
asked by Perl 04.10.2016 в 15:47
source

1 answer

1

The best way to capture keys is to use an event filter. They are very simple to create and we can customize them completely, which gives this mechanism an incredible versatility.

The idea is simple to implement:

The first thing is to create a new object that inherits from QObject . This object must overwrite the eventFilter method:

class FiltroDeEventosPersonalizado
  : public QObject
{
  Q_OBJECT

protected:

  bool eventFilter(QObject *obj, QEvent *event) override;
};

The implementation of the eventFilter method is the one that will manage the events to be captured. Basically it is about treating the events that interest us and return true when said event should be discarded.

Imagine that we only want to detect the key press A :

bool
FiltroDeEventosPersonalizado::eventFilter(
    QObject *obj,
    QEvent *event)
{
  if (event->type() == QEvent::KeyPress) {
    QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
    if( keyEvent->key() == Qt::Key_A )
     qDebug() << "Tecla 'A' presionada";
    return true;
  }

  return QObject::eventFilter(obj, event);
}

NOTE: If you do not want to discard the events just return false .

Now to use the class simply we install on that object we want to act on.

For the occasion, let's imagine that it is a QLineEdit :

FiltroDeEventosPersonalizado* filtro = new FiltroDeEventosPersonalizado;

QLineEdit* lineEdit = new QLineEdit;
lineEdit->installEventFilter(filtro);

For more information, check out this link .

Greetings.

    
answered by 04.10.2016 / 16:07
source