Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct


    Qt World Summit: Early-Bird Tickets

    Custom QGraphicsRectItem does not respond to key events

    General and Desktop
    1
    1
    491
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • M
      MadMan27 last edited by

      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";
      }
      @

      1 Reply Last reply Reply Quote 0
      • First post
        Last post