【发布时间】:2014-05-01 08:16:24
【问题描述】:
我有一个 QGraphicPixmapItem,其中包含一个 png 图像,出现在场景中。
图像本身是一个矩形图像。我的要求是,当我在鼠标移动事件上调整矩形图像的大小时,我应该能够调整图像的大小/缩放。 我可以通过拖动矩形图像的任意一侧来调整矩形的大小。
问题是,我可以通过拖动矩形图像的任何边来调整其大小,但原始图像严重扭曲,无法辨认。图片基本 在连续调整大小(扩大/缩小宽度或高度)时变成一块固体。 如何在 Qt 中实现图像的缩放/缩放而不会对原始图像造成太大的破坏?我所经历的不是像素化,而是更糟。
下面的代码是 QGraphicsPixmapItem 的 mouseMoveEvent() 的快照,实现了通过拖动矩形图像的右侧/左侧来调整矩形的大小。
void PersonSizeGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
const QPointF event_pos = event->pos();
const QPointF event_scene_pos = event->scenePos();
QPixmap current_pixmap = this->pixmap();
QImage current_image = current_pixmap.toImage();
QRect current_image_rect = current_image.rect();
QPoint current_top_left = current_image_rect.topLeft();
QPoint current_bottom_right = current_image_rect.bottomRight();
if((event->scenePos().x() > this->scene()->width()) || (event->scenePos().y() > this->scene()->height())
|| (event->scenePos().x() < 0) || (event->scenePos().y() < 0) )
{
return;
}
if( this->cursor().shape() == Qt::SizeHorCursor )
{
if(rect_right_condition)
{
new_rect = QRect( current_top_left, QPoint( event->pos().x(), current_bottom_right.y()) );
scaled_pixmap = QPixmap::fromImage(current_image.scaled(QSize(new_rect.width(),new_rect.height()),Qt::IgnoreAspectRatio,Qt::FastTransformation));
setPixmap(scaled_pixmap);
}
if(rect_left_condition)
{
new_rect = QRect( QPoint(event_pos.x(), 0), current_bottom_right );
scaled_pixmap = QPixmap::fromImage(current_image.scaled(QSize(new_rect.width(),new_rect.height()),Qt::IgnoreAspectRatio,Qt::FastTransformation));
setPixmap(scaled_pixmap);
QPoint new_top_left = new_rect.topLeft();
QPointF mapped_topLeft = mapToParent(QPointF(new_top_left.x(),new_top_left.y()));
this->setPos(mapped_topLeft);
rect_resize_occurred = true;
}
}
}
【问题讨论】:
-
黄金法则:在用户事件上更新
state,请求绘制事件,并在绘制方法中完成繁重的工作。在您的情况下,这意味着将第一个if之后的所有代码推送到油漆区。 -
@UmNyobe - 感谢您的建议。记下来了。
标签: qt png qgraphicsitem