0

I'm learning 3D using Qt and got a problem. I'm analyzing example: https://doc.qt.io/qt-5/qt3d-basicshapes-cpp-example.html

and now I wanted to modify it: when user presses a key (let's say 'w') something is moving (or just debug print at this stage). I tried to write a keyPressEvent function but I have no effect. Shall I do it in different way than in standard 2D app?

void SceneModifier::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
        case Qt::Key_W:
        {
            qDebug()<<"Key is pressed";
            break;
        }
        default:
        break;
     }
}

Cheers, Mikolaj

JJJ
  • 32,902
  • 20
  • 89
  • 102
Mikolaj
  • 43
  • 4

1 Answers1

0

SceneModifier inherits from QObject and it has not implemented the keyPressEvent method.

The keyPressEvent method belongs to the windows, in this case Qt3DWindow, so we create a class that inherits from it and implement the keyPressEvent method.

my3dwindow.h

#ifndef MY3DWINDOW_H
#define MY3DWINDOW_H

#include <Qt3DExtras/Qt3DWindow>

class My3DWindow: public Qt3DExtras::Qt3DWindow
{
    Q_OBJECT
public:
    My3DWindow(QScreen *screen = nullptr);
    ~My3DWindow();

protected:

    void keyPressEvent(QKeyEvent *ev);
};

#endif // MY3DWINDOW_H

my3dwindow.cpp

#include "my3dwindow.h"
#include <QDebug>
#include <QKeyEvent>

My3DWindow::My3DWindow(QScreen *screen):Qt3DExtras::Qt3DWindow(screen)
{

}

My3DWindow::~My3DWindow()
{

}

void My3DWindow::keyPressEvent(QKeyEvent *ev)
{
    switch (ev->key()) {
    case Qt::Key_W:
        qDebug()<<"Key is pressed";
        break;
    default:
        break;
    }
}

Change:

Qt3DExtras::Qt3DWindow *view = new Qt3DExtras::Qt3DWindow();

to:

My3DWindow *view = new My3DWindow();

main.cpp

[...]
#include "my3dwindow.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    My3DWindow *view = new My3DWindow();
    view->defaultFrameGraph()->setClearColor(QColor(QRgb(0x4d4d4f)));

 [...]

Complete code

eyllanesc
  • 235,170
  • 19
  • 170
  • 241