歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Qt實現圖像自適應窗口大小之scaled()函數使用

Qt實現圖像自適應窗口大小之scaled()函數使用

日期:2017/3/1 10:00:45   编辑:Linux編程

很多應用都需要顯示圖片,比如視頻類應用、拍照類應用,但是在大數情況下用戶都會改變窗口大小,以獲得最佳效果,在Qt中如果只設置了顯示圖片而沒有對自適應窗口做出設置,用戶拖拽邊框的時候,整個控件上就會出現大片空白部分,怎麼解決這個問題呢?

QImage、QPixmap等繪圖設備類都提供scaled()函數,下面是Qt文檔對於scaled()函數介紹:

函數原型:

QImage QImage::scaled ( int width, int height,
Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio,
Qt::TransformationMode transformMode = Qt::FastTransformation ) const

This is an overloaded function.

Returns a copy of the image scaled to a rectangle with the given width and height according to the given aspectRatioMode and transformMode.

If either the width or the height is zero or negative, this function returns a null image.

翻譯:
這是一個重載函數,按照指定的寬和高,根據縱橫比模式和轉換模式從原有圖像返回一個經過比例轉換的圖像,如果寬高為0,返回一個空圖像

所以,獲取控件的改變後的寬高,就能設定圖像轉換的寬高轉換比例,用scaled()的返回重新進行繪圖即可自適應窗口,以下是個例子:

  1. void Widget::paintEvent(QPaintEvent *)
  2. {
  3. QImage img((unsigned char*)im.data,im.cols,
  4. im.rows,QImage::Format_RGB888);
  5. QPainter painter(this);
  6. if(0==flag)
  7. painter.drawImage(0,0,nImg);
  8. /*
  9. 一定要加標記位判斷,控件在繪制之前的size為NULL,
  10. 所以scaled()返回值也為NULL,會提示nImg是空的
  11. */
  12. else if(1==flag)
  13. {
  14. nImg=img.scaled(width(),height());
  15. painter.drawImage(0,0,nImg);
  16. }
  17. }

Ps:

圖像是按比例變化的,如果放大很多,會出現模糊等現象。

Copyright © Linux教程網 All Rights Reserved