0

I wrote this piece of code, but I get this error:

"left of '->key' must point to class/struct/union/generic type".

Considering that GUI is a class derived from the QWidget class, how can I properly catch the pressing of a key?

void GUI::keyPressEvent(QKeyEvent *event)
{
    if (event->key()==Qt::Key_Up) {
        //do something
    }
}

The keyPressEvent is declared like this:

protected:    
    virtual void keyPressEvent(QKeyEvent *event);
frogatto
  • 28,539
  • 11
  • 83
  • 129
Ana
  • 3
  • 1
  • 5

1 Answers1

1

You have to include

#include <QKeyEvent>

then it should work as intended.


Apart from that you should use the Q_DECL_OVERRIDE macro like:

protected:    
    virtual void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE;

As @KubaOber mentioned, if you use a C++ Compiler supporting >=C++11 either by default or by you activating it with CONFIG += c++11 then you can use the override keyword instead.

deW1
  • 5,562
  • 10
  • 38
  • 54
  • I'd suggest `override` rather than `Q_DECL_OVERRIDE`, Qt 5.7 doesn't build on compilers that don't support that keyword. I used to suggest `Q_DECL_OVERRIDE` prior to Qt 5.7, of course, but now it's unnecessary. – Kuba hasn't forgotten Monica Oct 05 '16 at 17:05
  • @KubaOber good point. In general `Q_DECL_OVERRIDE` is the safe bet for older versions too :) since he didn't specify the version of Qt I went with the safe bet but adjusted it to mention both ways now. – deW1 Oct 05 '16 at 21:03
  • Oh...what if I can't include this library because apparently it doesn't exist? – Ana Oct 06 '16 at 13:30
  • @Ana are you using QtCreator or Visual Studio plugin / and which version if you're using QtCreator? – deW1 Oct 06 '16 at 13:38
  • @deW1 I am using Visual Studio plugin, and I have the Qt 5.6 version – Ana Oct 06 '16 at 16:54
  • @Ana if you write the include as I did and run it, does the error stay? – deW1 Oct 06 '16 at 17:23
  • @Ana for completion reasons consider accepting an answer if you feel like it solved your issue in a to you understandable matter. ( you do that by ticking the arrow on the left side of an answer ) – deW1 Oct 07 '16 at 14:28