Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Custom QGraphicsRectItem does not respond to key events
Forum Update on Monday, May 27th 2025

Custom QGraphicsRectItem does not respond to key events

Scheduled Pinned Locked Moved General and Desktop
1 Posts 1 Posters 577 Views
  • 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 Offline
    M Offline
    MadMan27
    wrote on last edited by
    #1

    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
    0

    • Login

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Get Qt Extensions
    • Unsolved