Time for action - Handling gamepad events

Let's start with adding the Qt Gamepad add-on to our project by editing the jrgame.pro file:

QT += core gui widgets gamepad

This will make the headers of the library available to our project and tell qmake to link the project against this library. Now add the following code to the constructor of the MyScene class:

QList<int> gamepadIds = QGamepadManager::instance()->connectedGamepads();
if (!gamepadIds.isEmpty()) {
    QGamepad *gamepad = new QGamepad(gamepadIds[0], this);
    connect(gamepad, &QGamepad::axisLeftXChanged,
            this, &MyScene::axisLeftXChanged);
    connect(gamepad, &QGamepad::axisLeftYChanged,
            this, &MyScene::axisLeftYChanged);
}

The code is pretty straightforward. First, we use QGamepadManager::connectedGamepads ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.