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. Keyboard input in custom QQuickPaintedItem
Qt 6.11 is out! See what's new in the release blog

Keyboard input in custom QQuickPaintedItem

Scheduled Pinned Locked Moved Unsolved General and Desktop
2 Posts 1 Posters 288 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.
  • kimorenK Offline
    kimorenK Offline
    kimoren
    wrote on last edited by
    #1

    As you can see code is really simple. Rectangle is successfully drawn on the screen, but pressing arrows does nothing. Is this a wrong method? If so, how can I process the keyboard input?

    Here are some parts of the code:
    (rest of the code is constructor that does nothing and a few useless functions)

    class NiceItem : public QQuickPaintedItem
    {
    
      ...
    
      public:
    
        ...
    
        void keyPressEvent(QKeyEvent * event);
        void paint(QPainter *painter);
    
      ...
    
    };
    
    void NiceItem::keyPressEvent(QKeyEvent * event)
    {
    
      if(event->key() == Qt::Key_Left)
        playerX--;
      else if(event->key() == Qt::Key_Right)
        playerX++;
      else if(event->key() == Qt::Key_Up)
        playerY--;
      else if(event->key() == Qt::Key_Down)
        playerY++;
    
    }
    
    void NiceItem::paint(QPainter *painter)
    {
    
      QPen pen(m_color, 2);
      painter->setPen(pen);
    
      QRectF rectangle(playerX, playerY, 80.0, 60.0);
      painter->drawRect(rectangle);
    
      update();
    
    }
    
    1 Reply Last reply
    0
    • kimorenK Offline
      kimorenK Offline
      kimoren
      wrote on last edited by
      #2

      I already solved the problem. It was enough to set focus to this item in constructor as following:

      setFlag(QQuickItem::ItemIsFocusScope, true);
      setFocus(true);
      
      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