Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

后端 未结 6 2009
长情又很酷
长情又很酷 2020-11-28 03:35

I use a QLabel to display the content of a bigger, dynamically changing QPixmap to the user. It would be nice to make this label smaller/larger depending on the space availa

6条回答
  •  迷失自我
    2020-11-28 04:20

    The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable. Additionally, to resize QLabel while honoring aspect ratio use:

    label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));
    

    The width and height can be set based on scrollarea.width() and scrollarea.height(). In this way there is no need to subclass QLabel.

提交回复
热议问题