Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show part of an image using QT?

Tags:

c++

qt

So, this is my problem: I have this very big image, and I want to show only a specific part of it. After the user pressing a specific key I want the image to move, showing another part of it. The transition from one part of the image to another have to be smooth, animated.

I tried using a QLabel to show the image but it always shows the center of the image, and I do not really know how to make the animation. What would you guys suggest?

like image 480
Paulo Facó Avatar asked Nov 16 '11 17:11

Paulo Facó


2 Answers

Interesting question. Here is something I just tested and seems to work.

Add a QGraphicsView with dimensions the dimensions of the part of the image you want to display, eg 100x100. Create a QGraphicsScene and add it to the view:

QGraphicsScene* pScene = new QGraphicsScene(this);
ui->graphicsView->setScene(pScene);

Now add your image into the scene. In my case I has an image in my resource file. The trick is to set the sceneRect to the position you want to display. I wanted to display an 100x100 part of the image starting from 0,300 :

pItem = pScene->addPixmap(QPixmap::fromImage(QImage(":/photos/image")));
pScene->setSceneRect(0,300,100,100);

In order to test the smooth moving I added a button which when clicked is triggering a slot called move. This slot simply updates the sceneRect. In my simple example I just move the image 100 pixels right. In a real world scenario you could also move it diagonally or vertically and check the image limits.

void move()
{
    for (unsigned i=currentX; i<currentX + 100; i++)
    {
    ui->graphicsView->scene()->setSceneRect(i,300,100,100);
    qApp->processEvents();
    }
    currentX += 100;
}

Notice the currentX variable. It is nothing more than the last image position. Also we must call the processEvents in order to "see" the image moving smoothly.

like image 194
pnezis Avatar answered Oct 12 '22 11:10

pnezis


You could use QPixmap::copy( int x, int y, int width, int height ) to copy a region of the image and display that.

like image 38
JediLlama Avatar answered Oct 12 '22 09:10

JediLlama