View Full Version : QGraphicsItem and focus for key input

9th February 2007, 00:12
I just started learning QT in the past week or so and I am an experienced programmer (java, c++, scripting, etc). I've looked through much of the documentation on the graphics view framework including the examples. Since I still did not completely understand, I took the mouse collision demo and started playing with it. What I want to do is restrict the scene to one mouse and be able to control that mouse with the arrow keys.

I'm calling


In the constructor of my item. I also thought that I could call


to get the focus for that item too - but my item is not yet visible when it is being constructed (it hasn't even been added to the scene yet!).

I got around this by utilizing the timerEvent, calling setFocus in there, and then it will accept keyPressEvent - but I don't want to do that! Thats crazy talk!

What is the correct way to handle this so that I can give my item focus after being added to the scene?

Do I do something like this?

void MyScene::keyPressEvent(QKeyEvent *event)
printf("scene pressed!!!\n");
QList<QGraphicsItem *> myItems = items();
foreach (QGraphicsItem *item, myItems)

And then somehow pass on the event to my item? Any thoughts would be appreciated!

9th February 2007, 05:28
Setting focus in the constructor doesnt make sense... all mouse cannot have focus..

so only the last one might have focus. A mouse will also have focus when mouse is clicked on it..

u need to override the keyPressEvent of the Mouse,,, not scene...
just check the attachment... I am able to change the po of the mouse on key press

also if u uncomment setFlags line in constuctor, u will be able to get focus on the mouse u click.. happy tweaking :D

9th February 2007, 20:13
Excellent example. Thanks so much!