我正在使用QGraphicsView缩放标签上的图像。但是当我缩小时,我想为缩小设置一个特定的限制。我使用以下代码
scene = new QGraphicsScene(this);
view = new QGraphicsView(label);
QPixmap pix("/root/Image);
Scene->addPixmap(pixmap);
view->setScene(scene);
view->setDragMode(QGraphicsView::scrollHandDrag);
在车轮事件的插槽中
void MainWindow::wheelEvent(QWheelEvent *ZoomEvent)
{
view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
double scaleFactor = 1.15;
if(ZoomEvent->delta() >0)
{
view->scale(scaleFactor,scaleFactor);
}
else
{
view->scale(1/scaleFactor,1/scaleFactor);
}
}
我希望图像在一定程度上不会缩小。我该怎么办? 我尝试设置QGraphicsView的最小大小,但这没有帮助。
谢谢你:)
答案 0 :(得分:7)
也许这样的事情会有所帮助:
void MainWindow::wheelEvent(QWheelEvent *ZoomEvent)
{
view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
static const double scaleFactor = 1.15;
static double currentScale = 1.0; // stores the current scale value.
static const double scaleMin = .1; // defines the min scale limit.
if(ZoomEvent->delta() > 0) {
view->scale(scaleFactor, scaleFactor);
currentScale *= scaleFactor;
} else if (currentScale > scaleMin) {
view->scale(1 / scaleFactor, 1 / scaleFactor);
currentScale /= scaleFactor;
}
}
正如您所看到的,这个想法是缓存当前的比例因子,如果它小于某个限制,则不会缩小。
答案 1 :(得分:1)
解决问题的另一种方法:
void GraphWidget::wheelEvent(QWheelEvent *event)
{
int scaleFactor = pow((double)2, - event->delta() / 240.0);
qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width();
if (factor < 0.5 || factor > 20)
return;
scale(scaleFactor, scaleFactor);
}
答案 2 :(得分:1)
这是另一种实现方式,其中从视图的变换矩阵获得当前缩放因子:
void View::wheelEvent(QWheelEvent *event) {
const qreal detail = QStyleOptionGraphicsItem::levelOfDetailFromTransform(transform());
const qreal factor = 1.1;
if ((detail < 10) && (event->angleDelta().y() > 0)) scale(factor, factor);
if ((detail > 0.1) && (event->angleDelta().y() < 0)) scale((1 / factor), (1 / factor));
}