简体   繁体   English

使用QImage和QRect显示图像

[英]Display image with QImage and QRect

I'm trying to make a game with Qt, but i can't load an image. 我正在尝试用Qt制作游戏,但我无法加载图像。

#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. 我知道如何使用QLabel显示图像,但我想使用QRect功能,所以我可以移动图像。

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. 你从image.rect()获得的rect只是一组数字。 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. 覆盖paintEvent(QPaintEvent*) ,并使用QPainterdrawImage例程之一绘制图像。
  2. Use a QLabel , set its icon, and use layouts to place it where you want. 使用QLabel ,设置其图标,并使用布局将其放置在您想要的位置。
  3. Use any type of QWidget , and set a style sheet with a background image. 使用任何类型的QWidget ,并设置带有背景图像的样式表 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. 如果您需要大量此类元素,请使用Graphics View框架。

There are a few other variations on those, depending on your exact requirements. 根据您的具体要求,还有其他一些变体。 Check out the painting examples , and the QPainter docs. 查看绘画示例QPainter文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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