Home > Net >  KeyPressEvent works crookedly in QLable
KeyPressEvent works crookedly in QLable

Time:10-19

I have a class that inherits QLabel. And it has keyPressEvent called, only after clicking on Tab

enum ElemntType { tBall, tWall, tGate, tPacman, tGhost, tWeakGhost, tPowerBall };
enum Dir { Left, Right, Up, Down, Stop }; 

class PacMan : public QLabel
{
    Q_OBJECT

public:
    explicit PacMan();
    ~PacMan() = default;
private:
    QMovie anim;
    Dir dir;
    ElementType type;
    int x, y;
private:
    void keyPressEvent(QKeyEvent* event);
};

and cpp file with it

PacMan::PacMan()
    : QLabel(), type(type), dir(Stop)
{ 
    setFocus();

    anim.setFileName("../Texture/startPacman.png");
    anim.start();
    setMovie(&anim);
    setFixedSize(20, 20);
    
    x = pos().x();
    y = pos().y();
}

void PacMan::keyPressEvent(QKeyEvent* event)
{
    switch (event->nativeVirtualKey())
    {
    case Qt::Key_A:
        dir = Left;
        
        anim.stop();
        anim.setFileName("../Texture/lPacman.gif");
        anim.start();

        move(--x, y);
        break;
    case Qt::Key_D:
        dir = Right;

        anim.stop();
        anim.setFileName("../Texture/rPacman.gif");
        anim.start();

        move(  x, y);
        break;
    }
}

When I try to press keys nothing happens (keyPressEvent is not called at all), but if I press Tab then keyPressEvent will work fine. Why is this happening and how to fix it?

main.cpp

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    QGraphicsView view(new QGraphicsScene);
    PacMan* move = new PacMan();
    move->setFocusPolicy(Qt::StrongFocus);
    view.scene()->addWidget(move);
    view.show();
    return app.exec();
}

CodePudding user response:

With Qt::StrongFocus, your widget is made focus-able using tab and mouse. However, it does not necessarily get the focus. One way to force it is to set Qt::NoFocus for all other widgets before setting your Qt::StrongFocus. It can be done with (taken from the answer to: How to set Focus on a specific widget):

for (auto widget : findChildren<QWidget*>())
    if (! qobject_cast<QOpenGlWidget*>(widget)) widget->setFocusPolicy(Qt::NoFocus);

CodePudding user response:

I just called setFocus together after view.show()

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    QGraphicsView view(new QGraphicsScene);
    PacMan* move = new PacMan();
    view.scene()->addWidget(move);
    view.show();
    move->setFocus();
    return app.exec();
}
  •  Tags:  
  • c qt
  • Related