C++ - Qt Framework - Moving a shape with arrow keys

Playing with the keyboard is an interesting way of learning the Qt framework.

In this tutorial we are going see, indeed, how to use the arrow keys in order to move a shape.

This shape is a circle, with only few properties to handle with.

Let's get started.

First of all

In this Qt example we are going to use an interface to specify that our shape is movable.

We'll also define a constructor for this shape in order to set their useful properties.

This implementation is in the MainWindow class.

Only one line to create it, very simple.

The whole shape has it own class named MovingShape with some methods such as move(), paintEvent(), keyPressed() and a lot of get() and sets().

The move() method takes an IMovable::Direction enum as parameter and we'll use this choice (up, down, left or right) to move our shape.

The paintEvent() and keyPressEvent() are protected methods that are handled directly by Qt.

For example, each time a key is pressed on the keyboard, the keyPressEvent() method is called by Qt.

This is a method inherited from the QWidget class, and as our MovingShape inherits from QWidget we can have acces to all its protected and public methods.

It means that you don't need to call them in you code because they'll be called automatically by the framework.

So we use the keyPressEvent() to catch an arrow key pressed and we use the move() method to get the direction received.

And of course we draw an ellipse and a circle with the paintEvent() method

Code

To download the code, get it from my GitHub:

Conclusion

You are now able to use the keyboard to move a shape with Qt framework.

Good job, you did it! smiley

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.