Question

I have an image onto which I draw a Rectangle as such. After that I am attempting to copy the contents of the rectangle onto another QLabel. This seems to work however i cannot seem to align the copied image starting from the left top corner of the image. Here is what I am doing

QPixmap original_image; 
original_image.load("c:\\Images\\myimg.jpg");
original_image = original_image.scaled(ui.label->size().width(),ui.label->size().height());

//-----------------------------------------------------------------------
//Draw rectangle on this
QPixmap target_two(ui.label->size().width(),ui.label->size().height());
target_two.fill(Qt::transparent);     

QPixmap target(ui.label->size().width(),ui.label->size().height());
target.fill(Qt::transparent);    

QPainter painter(&target);
QPainter painter_two(&target_two);


QRegion r(QRect(0, 0, ui.label->size().width(), ui.label->size().height()), QRegion::RegionType::Rectangle);  //Region to start copying
painter.setClipRegion(r);
painter.drawPixmap(0, 0, original_image); //Draw the original image in the clipped region 


QRectF rectangle(x_start,y_start,clipRegion);
painter.drawRoundedRect(rectangle,0,0); //Last two parameters define the radius of the corners higher the radius more rounded it is

             QRegion r_two(rectangle.toRect(), QRegion::RegionType::Rectangle); 
             painter_two.setClipRegion(r_two);
             painter_two.drawPixmap(0,0,target); 


ui.label->setPixmap(target);    

ui.label_2->setPixmap(target_two);

The bottom picture is the image with the red rectangle in it and that is fine. The top picture is a copy of the contents of the square.The only problem is its not starting from the top left corner.

Any suggestion on why I am not getting the copied content on the top left corner.

Was it helpful?

Solution

The problem in your logic is that both target and target_two images have the same sizes - size of the label, and you draw the copied image in the same position as it was in the initial label. So far so good. I would solve this by the following code:

[..]
// This both lines can be removed.
// QRegion r_two(rectangle.toRect(), QRegion::RegionType::Rectangle); 
// painter_two.setClipRegion(r_two);

// Target rect. in the left top corner.
QRectF targetRect(0, 0, rectangle.width(), rectangle.height());
QRectF sourceRect(rectangle);
// Draw only rectangular area of the source image into the new position.
painter_two.drawPixmap(targetRect, target, sourceRect);
[..]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top