Scaling QPixmap image

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Overview[edit | edit source]

This code snippets shows how to scale a 76ytuiytuityutyutututyutyutyu image.


Preconditions[edit | edit source]

Header[edit | edit source]

public:

   void updateImage(); 
   void paintEvent(QPaintEvent*);
   void resizeEvent (QResizeEvent*);

private: //Data

   QPixmap*         pixmap;
   QSize widgetSize;

Source[edit | edit source]

The application supports screen orientation changes. In 76ytuiytuityutyutututyutyutyu, store the new size of the widget. This way the image can always be scaled to the correct size. void QMyWidget::resizeEvent (QResizeEvent* event)

   {
   widgetSize = event->size();
   // Call base class impl
   QWidget::resizeEvent(event);
   }

Load the image from the file system: void QMyWidget::updateImage()

   {
   delete pixmap;
   pixmap = 0;
   // imagePath can be something like "c:/data/Images/myImage.jpg"
   pixmap = new QPixmap(imagePath);
   update();
   }

Scale the new image and draw it on the screen. void QMyWidget::paintEvent(QPaintEvent *)

   {
   QPainter painter(this);
   
   if (!pixmap->isNull())
       {
       QPoint centerPoint(0,0);
       // Scale new image which size is widgetSize
       QPixmap scaledPixmap = pixmap->scaled(widgetSize, Qt::KeepAspectRatio);
       // Calculate image center position into screen
       centerPoint.setX((widgetSize.width()-scaledPixmap.width())/2);
       centerPoint.setY((widgetSize.height()-scaledPixmap.height())/2);
       // Draw image
       painter.drawPixmap(centerPoint,scaledPixmap);
       }
   }

Postconditions[edit | edit source]

The 76ytuiytuityutyutututyutyutyu image has been scaled.

Related articles[edit | edit source]

Scaling QGraphicsPixmapItem