Possible to implement Keyevent in a class that inherits from Qwidget instead of Qframe

Asked

Viewed 45 times

0

My class:

class Jogador : public QWidget {
Q_OBJECT

public:
    Jogador(QWidget* parent = NULL);
    void draw();
    void paintEvent(QPaintEvent* event);
    void keyPressEvent(QKeyEvent* event);

private:

    int x,y,w,h;
    QVBoxLayout* layout;
};   

My Function:

void Jogador::keyPressEvent(QKeyEvent* event) {
    QWidget::keyPressEvent(event);

    switch (event->key()) {
    case Qt::Key_Up:
        x+=20;
        repaint();
        break;
    default:
        break;
    }
}

The question is: will I be able to make the keystroke event work in a class that inherits from QWidget, or only QFrame?

my main is like this:

#include<QApplication> 
   #include<tabuleiro.h>
   #include<jogador.h>
   #include<QWidget>
   int main(int argc, char* argv[]){

    QApplication app(argc, argv);

    QWidget window;
    Tabuleiro t(&window);
    Jogador j(&window);
    window.show();



    return app.exec();
    return 0;
   }

1 answer

0

A QFrame is nothing more than a QWidget which is rendered with an extra edge. It does not add any other functionality that has anything to do with any event. That said, whatever you do and run in one QFrame, will also work on a QWidget.

Now, to your code: In an event you must either deal with it, or pass it on to an ancestor who will deal with it. In your case you are first asking your father (the QWidget) to handle the event. And then you process it yourself. It doesn’t fail to work, but it’s not ideal. Here a corrected version:

void Jogador::keyPressEvent(QKeyEvent* event) {
    switch (event->key()) {
    case Qt::Key_Up:
        x += 20;
        repaint();
        break;
    default:
        QWidget::keyPressEvent(event);
        break;
    }
}

That being said, there is nothing else wrong with how you implemented it. It works.

  • Check out my main, I think there must be something wrong. because I can not make call the Keyevent

Browser other questions tagged

You are not signed in. Login or sign up in order to post.