File indexing completed on 2024-04-28 15:39:19
0001 /* 0002 SPDX-FileCopyrightText: 2022 Friedrich W. H. Kossebau <kossebau@kde.org> 0003 0004 SPDX-License-Identifier: LGPL-2.1-or-later 0005 */ 0006 0007 #include "imageview.hpp" 0008 0009 // Qt 0010 #include <QLabel> 0011 #include <QPalette> 0012 #include <QPixmap> 0013 #include <QScrollArea> 0014 #include <QVBoxLayout> 0015 0016 namespace Kodaskanna 0017 { 0018 namespace ImageSource 0019 { 0020 0021 // work-around for QLabel not having native proportional scaling of pixmaps 0022 class ProportionalImageLabel : public QLabel 0023 { 0024 public: 0025 ProportionalImageLabel() = default; 0026 0027 /// Reinvent setter original method 0028 void setPixmap(const QPixmap &pixmap) 0029 { 0030 m_originalPixmapWidth = pixmap.width(); 0031 m_originalPixmapHeight = pixmap.height(); 0032 0033 adjustContentsMargins(); 0034 QLabel::setPixmap(pixmap); 0035 } 0036 0037 public: // QWidget API 0038 void resizeEvent(QResizeEvent *event) override 0039 { 0040 adjustContentsMargins(); 0041 QLabel::resizeEvent(event); 0042 } 0043 0044 private: 0045 void adjustContentsMargins() 0046 { 0047 if ((m_originalPixmapWidth <= 0) || (m_originalPixmapHeight <= 0)) { 0048 return; 0049 } 0050 0051 const int width = this->width(); 0052 const int height = this->height(); 0053 0054 if ((width <= 0) || (height <= 0)) { 0055 return; 0056 } 0057 0058 if (width * m_originalPixmapHeight > height * m_originalPixmapWidth) { 0059 const int horizontalMargin = (width - (m_originalPixmapWidth * height / m_originalPixmapHeight)) / 2; 0060 setContentsMargins({horizontalMargin, 0, horizontalMargin, 0}); 0061 } else { 0062 const int verticalMargin = (height - (m_originalPixmapHeight * width / m_originalPixmapWidth)) / 2; 0063 setContentsMargins({0, verticalMargin, 0, verticalMargin}); 0064 } 0065 } 0066 0067 private: 0068 int m_originalPixmapWidth = 0; 0069 int m_originalPixmapHeight = 0; 0070 }; 0071 0072 ImageView::ImageView(QWidget *parent) 0073 : QWidget(parent) 0074 , m_scrollArea(new QScrollArea) 0075 , m_imageLabel(new ProportionalImageLabel) 0076 { 0077 m_imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); 0078 m_imageLabel->setScaledContents(true); 0079 0080 m_scrollArea->setBackgroundRole(QPalette::Dark); 0081 m_scrollArea->setAlignment(Qt::AlignCenter); 0082 m_scrollArea->setWidget(m_imageLabel); 0083 m_scrollArea->setWidgetResizable(true); 0084 0085 auto *layout = new QVBoxLayout; 0086 layout->setContentsMargins({}); 0087 layout->addWidget(m_scrollArea); 0088 setLayout(layout); 0089 } 0090 0091 ImageView::~ImageView() = default; 0092 0093 void ImageView::setImage(const QImage &image) 0094 { 0095 m_image = image; 0096 m_imageLabel->setPixmap(QPixmap::fromImage(image)); 0097 } 0098 0099 } 0100 }