Search code examples
c++qtzoomingqwidgetqscrollarea

Making zooms on an QWidget while inside a QScrollArea


I want to show a pixmap on Qt and make able to zoom, I'm using a QWidget inside a QScrollArea, but the ScrollBars of the area are not working, when I zoom on the image, the image gets bigger, but there is no scrollbars so i can move, let me show you some code :

Here is how I'm declaring the Widgets :

_scroll = new QScrollArea(_frame);
_image_widget = new QImageWidget(_scroll);      
_scroll->setBackgroundRole(QPalette::Dark);
_scroll->setWidget(_image_widget);
_scroll->setWidgetResizable(true);

_frame is the area where i should show the hole thing, _image_widget is an object of QImageWidget which is inheriting from QWidget

if I dont use this : _scroll->setWidgetResizable(true); the image is just too small

And here is how I deal with the Zoom :

 void QImageWidget::paintEvent(QPaintEvent *ev) {
    QPainter p(this);
    if(pixmap() != NULL){
        int w = pixmap()->width();
        int h = pixmap()->height();
        QPixmap map = pixmap()->scaled(w*zoom,h*zoom,Qt::KeepAspectRatio);
        p.drawPixmap(0, 0, map );
    }     
}

void QImageWidget::wheelEvent ( QWheelEvent * e )
    {
    int x = e->pos( ).x();
    int y = e->pos( ).y();

    if (e->delta() > 0) 
        zoom *= 2;
    else
        if(zoom > 1)
    zoom /= 2;
}

SO the problem is as I said, the image keeps getting bigger when i'm zooming until it takes the hole area of the QScrollArea and then when I keep zooming, the zoom is working but there is no ScrollBars so i can see the other part of the Image.

Tell me if i'm not understandable ! thanks !


Solution

  • I found the answer to my question, all i had to do is add this resize(sizeHint()*zoom); before drawing the pixmap :

    void QImageWidget::paintEvent(QPaintEvent *ev) {
       QPainter p(this);
       if(pixmap() != NULL){
          int w = pixmap()->width();
          int h = pixmap()->height();
          QPixmap map = pixmap()->scaled(w*zoom,h*zoom,Qt::KeepAspectRatio);
          resize(sizeHint()*zoom);
          p.drawPixmap(0, 0, map );
       }     
     }
    

    the pixels were updated but not the size of the widget !