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. Any better way to use keyEvent?

Any better way to use keyEvent?

Scheduled Pinned Locked Moved General and Desktop
2 Posts 1 Posters 563 Views 1 Watching
  • 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.
  • K Offline
    K Offline
    kamhagh
    wrote on last edited by
    #1

    hi, i was trying too see how keypress librarie is :) so i first made something that increases posX on pressevents, but i didn't like the way that my ball moved, so i created this, but i don't feel like this is a good way to do this (resources ect, i know in here it just works but if i made a game or something that wouldn't be good)

    @
    void Game::keyPressEvent(QKeyEvent *event)
    {
    switch(event->key())
    {
    case Qt::Key_W:
    KW = true;
    break;
    case Qt::Key_S:
    KS = true;
    break;
    case Qt::Key_A:
    KA = true;
    break;
    case Qt::Key_D:
    KD = true;
    break;
    default:
    break;
    }
    }

    void Game::keyReleaseEvent(QKeyEvent *event)
    {
    switch(event->key())
    {
    case Qt::Key_W:
    KW = false;
    break;
    case Qt::Key_S:
    KS = false;
    break;
    case Qt::Key_A:
    KA = false;
    break;
    case Qt::Key_D:
    KD = false;
    break;
    default:
    break;
    }
    }

    void Game::mousePressEvent(QMouseEvent *event)
    {
    posY = event->y() - 25;
    posX = event->x() - 25;
    }

    void Game::timerEvent(QTimerEvent *e)
    {
    //-Y-
    if(KW == true)
    posY-=3;
    if(KS == true)
    posY+=3;

    //-X-
    if(KD == true)
        posX+=3;
    if(KA == true)
        posX-=3;
    
    if(posY > height() - 50)
        posY = height() -50;
    if(posY < 0)
        posY = 0;
    
    if(posX > width() - 50)
        posX = width() -50;
    if(posX < 0)
        posX = 0;
    
    repaint();
    

    }@

    is my code fine? or can you recommend me someother way !?

    1 Reply Last reply
    0
    • ? This user is from outside of this forum
      ? This user is from outside of this forum
      Guest
      wrote on last edited by
      #2
      This post is deleted!
      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