Possible to implement KeyEvent in a class that inherits from Qwidget instead of QFrame

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 Role:

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

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

The question is: can I make the key event work in a class that inherits from QWidget , or only QFrame ?

My main looks 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;
   }
    
asked by anonymous 30.05.2015 / 22:10

1 answer

0

A QFrame is nothing more than a QWidget that is rendered with one more border. It does not add any other functionality that has anything to do with any event. That being said, everything you do and work on QFrame , will also work on QWidget .

Now, to your code: In an event you must either deal with it, or pass it on to an ancestor who will deal. In your case you are first asking your parent ( QWidget ) to handle the event. And in the sequence you sue him yourself. This does not stop working, but it is not ideal. Here is 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, nothing else is wrong with how you implemented it. It works.

    
30.05.2015 / 22:33