5. Keyboard data monitoring of Qt Project

Keyboard data monitoring:

Similarly, the detection of the keyboard is very similar to that of the mouse, both of which are based on QWidget.

Step1: Add the relevant components that the module needs to use in the UI design, as shown below:

View Code

From the ui design, we can clearly see that there are two buttons, several Labels, a Frame, and so on.

Step2: We add the execution function of our corresponding event in the widget.cpp file:

  func1:keyPressEvent   func2:keyPressEvent

void Widget::keyPressEvent(QKeyEvent *e)
{
    int x,y,dis;
    x = ui->pushButton_3->x();
    y = ui->pushButton_3->y(); switch(e->key()) { case Qt::Key_W : dis = y>40 ? 10:0; ui->pushButton_3->move(x,y-dis); break; case Qt::Key_S : dis = y<190 ? 10:0; ui->pushButton_3->move(x,y+dis); break; case Qt::Key_A : dis = x>190 ? 10:0; ui->pushButton_3->move(x-dis,y); break; case Qt::Key_D : dis = x<370 ? 10:0; ui->pushButton_3->move(x+dis,y); break; default : break; } ui->pushButton->setText(tr("%1,%2").arg(x).arg(y)); } void Widget::keyReleaseEvent(QKeyEvent *e) { ui->pushButton_2->setText(tr("%1").arg(e->key())); }

Also declare these two functions in the widget.h header file:

protected:
    void keyPressEvent(QKeyEvent *);
    void keyReleaseEvent(QKeyEvent *);

The above two basic steps complete the establishment of the entire project, and the next step is to compile and run! (The way to use Demo is that the WSAD on the keyboard corresponds to the front, back, left, and right directions, and the circle on the Frame will move with the front, back, left, and right directions of the keyboard)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324886960&siteId=291194637