Switch object focus in QT

I'm trying to make a simple project where I move two rectangles on a screen at the same time with different controls for each but I'm having trouble controlling more than one. Setting focus on one rectangle removes the focus from the other and I can't figure out how to get it to flip, though I've tried many times. Maybe I'm just handling this wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  RectCollision::RectCollision()
{
    scene = new QGraphicsScene();

    rectA = new MovementInput(0);
    rectB = new MovementInput(1);

    scene->addItem(rectA);
    scene->addItem(rectB);

    rectA->setFlag(QGraphicsItem::ItemIsFocusable);
    rectB->setFlag(QGraphicsItem::ItemIsFocusable);

    rectA->setFocus();
    rectB->setFocus();

    view = new QGraphicsView(scene);
    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setFixedSize(600,600);
    view->setSceneRect(0,0, 600, 600);  
    view->show();
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
MovementInput::MovementInput(bool t)
{
    type = t;
    if(type)
    {
       setRect(150,300,60,60);
    }
    else
    {
        setRect(450,300,60,60);
    }

}

void MovementInput::keyPressEvent(QKeyEvent *event)
{
    if(type)
    {
        if(event->key() == Qt::Key_Left)
        {
            setPos(x() - 5, y());
        }
        if(event->key() == Qt::Key_Right)
        {
            setPos(x() + 5, y());
        }
        if(event->key() == Qt::Key_Up)
        {
            setPos(x(), y() - 5);
        }
        if(event->key() == Qt::Key_Down)
        {
            setPos(x(), y() + 5);
        }
    }

    else
    {
        if(event->key() == Qt::Key_A)
        {
            setPos(x() - 5, y());
        }

        if(event->key() == Qt::Key_D)
        {
            setPos(x() + 5, y());
        }
        if(event->key() == Qt::Key_W)
        {
            setPos(x(), y() - 5);
        }
        if(event->key() == Qt::Key_S)
        {
            setPos(x(), y() + 5);
        }
    }

    QList<QGraphicsItem*> colliding_items = collidingItems();
    int n = colliding_items.size();
    for(int i=0; i<n; ++i)
    {
        qDebug() << "Collision Detected";
    }
}
Subclass QGraphicsScene and detect your keypress(es) there.
Topic archived. No new replies allowed.