Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Keyboard input in custom QQuickPaintedItem



  • 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();
    
    }
    


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

    setFlag(QQuickItem::ItemIsFocusScope, true);
    setFocus(true);
    

Log in to reply