Qt Forum

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

    Update: Forum Guidelines & Code of Conduct


    Qt World Summit: Early-Bird Tickets

    Unsolved Problem with item positioning

    General and Desktop
    2
    2
    324
    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.
    • R
      robinfriedli last edited by

      Hi.

      I'm trying to write a simple Snake game with Qt but I have issues with the positioning of the fruit. When the Snake eats the fruit (meaning that if the SnakeHead collides with the fruit) the Fruit should respawn in a random location on the screen.

      For that, I use the height and width of the QGraphicsView. As long as I don't resize the window this works fine, but as soon as I do the Fruit will eventually spawn outside of the visible view.

      I did some debugging and found that the coordinates are fine. E.g. when I enter fullscreen mode, the QGraphicsView size is 1440x900, as expected on my MacBook Pro, since it has a 1440x900 system resolution despite the 2880x1800 display resolution.

      But when the Fruit spawns at, for example, width=1237, height=626, it is not visible. Only when I scale the screen to 1920x1200 I can see it to the very right.

      This is how I place the Fruit:

      void Game::spawnFruit(){
          int width = rand() % (QGraphicsView::width() - 100);
          int height = rand() % (QGraphicsView::height() - 100);
          f1->setPos(width, height);
      
          QList<QGraphicsItem*> cItems = scene->collidingItems(f1);
          if(!cItems.empty()) {
              spawnFruit();
          }
      }
      

      Again, this only happens when enlarging the window, it works fine if I make it smaller or launch it at full resolution. It probably has something to do with this:

      Game::Game(QWidget *parent): QGraphicsView(parent){
          scene = new QGraphicsScene(0,0,800,600);
          setScene(scene);
      }
      

      So basically, as soon as the window / QGraphicsView becomes bigger than the QGraphicsScene this problem occurs. If it's smaller, then the window becomes scrollable but the Fruit always spawns within the size of the window. Is there a way to make this responsive?

      I'm using Qt Creator 4.5.0 based on Qt 5.10.0.

      Thanks in advance.

      1 Reply Last reply Reply Quote 0
      • A
        Asperamanca last edited by

        When you place fruit, you do that within the GraphicsScene. So it's the size of the GraphicsScene that matters, not the size of the GraphicsView.
        QGraphicsScene::sceneRect() might be what you need.

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