Отображение изображения в Qt по размеру метки

Для C++ я - большой поклонник Общепринятая истина C++: Существенное Промежуточное Программирование , мне нравится этот, оно организовано в маленькие разделы (обычно меньше чем 5 страниц за тему), Таким образом, для меня легко захватить его и читать на понятиях, которые я должен рассмотреть.

Это - необходимость чтение для меня накануне ночью и на плоскости к собеседованию.

28
задан Tetsujin no Oni 19 June 2014 в 13:54
поделиться

1 ответ

Я также отвечу на свой вопрос, но не буду отмечать его как решение, потому что я попросил простой вопрос, который был дан выше. В конце концов, я использовал не слишком простое решение, поэтому каждый, кому нужно сделать что-то похожее и у него есть время поиграть, вот мой последний рабочий код. Идея состоит в том, чтобы расширить QLabel и перегрузить setPixmap и методы drawEvent.

QPictureLabel.hpp (заголовочный файл)

#include "QImage.h"
#include "QPixmap.h"
#include "QLabel.h"

class QPictureLabel : public QLabel
{
private:
    QPixmap _qpSource; //preserve the original, so multiple resize events won't break the quality
    QPixmap _qpCurrent;

    void _displayImage();

public:
    QPictureLabel(QWidget *aParent) : QLabel(aParent) { }
    void setPixmap(QPixmap aPicture);
    void paintEvent(QPaintEvent *aEvent);
};

QPictureLabel.cpp (реализация)

#include "QPainter.h"

#include "QPictureLabel.hpp"

void QPictureLabel::paintEvent(QPaintEvent *aEvent)
{
    QLabel::paintEvent(aEvent);
    _displayImage();
}

void QPictureLabel::setPixmap(QPixmap aPicture)
{
    _qpSource = _qpCurrent = aPicture;
    repaint();
}

void QPictureLabel::_displayImage()
{
    if (_qpSource.isNull()) //no image was set, don't draw anything
        return;

    float cw = width(), ch = height();
    float pw = _qpCurrent.width(), ph = _qpCurrent.height();

    if (pw > cw && ph > ch && pw/cw > ph/ch || //both width and high are bigger, ratio at high is bigger or
        pw > cw && ph <= ch || //only the width is bigger or
        pw < cw && ph < ch && cw/pw < ch/ph //both width and height is smaller, ratio at width is smaller
        )
        _qpCurrent = _qpSource.scaledToWidth(cw, Qt::TransformationMode::FastTransformation);
    else if (pw > cw && ph > ch && pw/cw <= ph/ch || //both width and high are bigger, ratio at width is bigger or
        ph > ch && pw <= cw || //only the height is bigger or
        pw < cw && ph < ch && cw/pw > ch/ph //both width and height is smaller, ratio at height is smaller
        )
        _qpCurrent = _qpSource.scaledToHeight(ch, Qt::TransformationMode::FastTransformation);

    int x = (cw - _qpCurrent.width())/2, y = (ch - _qpCurrent.height())/2;

    QPainter paint(this);
    paint.drawPixmap(x, y, _qpCurrent);
}

Использование : аналогично использованию обычной метки для отображения изображения без setScaledContents

img_Result = new QPictureLabel(ui.parent);
layout = new QVBoxLayout(ui.parent);
layout->setContentsMargins(11, 11, 11, 11);
ui.parent->setLayout(layout);
layout->addWidget(img_Result);

//{...}

QPixmap qpImage(qsImagePath);
img_Result->setPixmap(qpImage);
14
ответ дан 28 November 2019 в 02:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: