Custom QGraphicsRectItem does not respond to key events



  • I have created a class called MyRect that derives from QGraphicsRectItem. I overided the keyPressEvent to just print out a message. I put my rect item in a scene, set its itemisfocusable flag, and called it's setFocus() method. However, when I press keys, my item's keyPressEvent() method does not run. What is wrong? Here is the code:

    ==main.cpp==
    @#include <QApplication>
    #include "MyRect.h"
    #include <QGraphicsScene>
    #include <QGraphicsView>

    #include <QDebug>
    int main(int argc, char *argv[]){
    QApplication a(argc, argv);

    // create a scene
    QGraphicsScene * scene = new QGraphicsScene();
    
    // create an item to add to the scene
    MyRect * rect = new MyRect();
    rect->setRect(0,0,100,100); // change the rect from 0x0 (default) to 100x100 pixels
    
    // add the item to the scene
    scene->addItem(rect);
    
    // give the item focus
    rect->setFlag(QGraphicsItem::ItemIsFocusable,true);
    rect->setFocus();
    
    // create a view to visualize the scene
    QGraphicsView * view = new QGraphicsView(scene);
    
    // show the view
    view->show();
    
    return a.exec&#40;&#41;;
    

    }
    @

    ==MyRect.h==
    @#ifndef MYRECT_H
    #define MYRECT_H

    #include <QGraphicsRectItem>
    #include <QKeyEvent>

    class MyRect: public QGraphicsRectItem{
    public:
    MyRect();
    void keyPressEvent(QGraphicsSceneEvent *event);
    };

    #endif // MYRECT_H@

    ==MyRect.cpp==
    @#include "MyRect.h"

    #include <QDebug>
    MyRect::MyRect(): QGraphicsRectItem(){

    }

    void MyRect::keyPressEvent(QGraphicsSceneEvent *event){
    qDebug() << "my rect knows you pressed a key! :D";
    }
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.