I am writing a C++ game using Qt. As this is the first time, I am trying to understand how the structure should be.
I have two objects derived from the type QGraphicsRectItem which appear as boxes on the screen, which will each represent a player. I want to make them move independently in response to key presses, with a different set of keys assigned to the motion of each object. These are added to a QGraphicsScene object, which is set by a QGraphicsView inherited object.
As only one of these can be focused at any given point of time, and thus respond to key press events, I have defined a function in a class which inherits from QGraphicsView (and is used as a view for viewing the scene) that receives all the key press events. Its constructor receives pointers to the two box objects, and sends the required information (by setting a variable) to the appropriate object through the pointer based on the key press.
I have a few questions regarding this:
- Is QGraphicsRectItem (or QGraphicsItem) the correct class for creating such "objects"? I see that there is a QObject class, but I could not understand where it is meant to be used.
- Sending pointers of the box objects to the constructor of the view during initialization doesn't seem right. What would be a more appropriate way to design this? The idea is that based on the key pressed, the corresponding box should respond. The problem is, how does this class access the object, unless it is declared inside it or passed as an argument?
- Is there a better or more commonly used way to handle the requirement of different objects responding to different key presses, even if done simultaneously? I have seen suggestions for using Event filters, which would pass the event using postEvent. However, event filters send messages to objects of type QObject, which is not what I am currently using. Additionally, the question again arises - who would receive the key press events? How would it know about the existence of the box objects?
I have been reading about design patterns. Is there any particular pattern that would be suitable for this?
Thank you.