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:

    @#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
    // give the item focus
    // create a view to visualize the scene
    QGraphicsView * view = new QGraphicsView(scene);
    // show the view
    return a.exec&#40;&#41;;


    @#ifndef MYRECT_H
    #define MYRECT_H

    #include <QGraphicsRectItem>
    #include <QKeyEvent>

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

    #endif // MYRECT_H@

    @#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.