我有一个图像,我在其上绘制一个矩形。之后我试图将矩形的内容复制到另一个QLabel上。这似乎工作,但我似乎无法从图像的左上角开始对齐复制的图像。这就是我正在做的事情
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);
底部图片是带有红色矩形的图片,很好。 顶部的图片是广场内容的副本。唯一的问题是它不是从左上角开始的。
有关我为何没有在左上角收到复制内容的任何建议。
答案 0 :(得分:1)
逻辑上的问题是target和target_two图像都具有相同的大小 - 标签的大小,并且您将复制的图像绘制在与初始标签中相同的位置。到现在为止还挺好。我将通过以下代码解决这个问题:
[..]
// 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);
[..]