简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM