Kanghu
Kanghu

Reputation: 591

Display image with QImage and QRect

I'm trying to make a game with Qt, but i can't load an image.

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
image.load("F:/My Workspace/sprite.png");
rect = image.rect();
rect.moveTo(5,5);
}

This is the constructor of the window. The image doesn't show up. I know how to display image using QLabel, but i want to use QRect features so i can move the image.

Upvotes: 3

Views: 3057

Answers (1)

Mat
Mat

Reputation: 206859

That's not how things work. The image isn't displayed because you're not doing anything that would display it. And the rect you get from image.rect() is just a set of numbers. It is not connected to the image in any way, so changing it won't alter the image whether it is displayed or not.

Here are four ways to do what you want:

  1. Override paintEvent(QPaintEvent*), and draw the image where you want using one of QPainter's drawImage routines.
  2. Use a QLabel, set its icon, and use layouts to place it where you want.
  3. Use any type of QWidget, and set a style sheet with a background image. Again, use layouts (or absolute positioning) to get it where you want.
  4. Use the Graphics View framework if you need a lot of such elements.

There are a few other variations on those, depending on your exact requirements. Check out the painting examples, and the QPainter docs.

Upvotes: 4

Related Questions