Home > Enterprise >  How to display image in ratio as PreserveAspectFit in Qt Widgets
How to display image in ratio as PreserveAspectFit in Qt Widgets

Time:09-17

In qml, I can simply do this

    Image {
        anchors.fill: parent
        source: "/path/to/coo/image"
        fillMode: Image.PreserveAspectFit
    }

I don't want to use QML due to its ties with JavaScript. How can I do this with Widgets ?

I tried using QLabel but it has no option to set aspect ratio or fillMode. I think I can manually scale the pixmap and then set it to QLabel but that wont be reactive (resize image when window is resized) like QML. Isn't there any image specefic widget in Qt to do this ?

CodePudding user response:

you can simply do that:

QPixmap pixmap("background.png");
pixmap.scaled(pixmap.size(), Qt::KeepAspectRatio);

You can manipulate the size value as you wanna. If you wanna, you can catch the size of the QLabel that the pixmap is laying on.

CodePudding user response:

A possible solution is to use QGraphicsView, QGraphicsScene and QGraphicsPixmapItem:

#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QPixmap>

class Viewer: public QGraphicsView{
public:
    Viewer(QWidget *parent = nullptr): QGraphicsView(parent){
        setScene(new QGraphicsScene(this));
        m_pixmapItem = scene()->addPixmap(QPixmap());
        setAlignment(Qt::AlignCenter);
    }
    QPixmap pixmap() const{
         return m_pixmapItem->pixmap();
    }
    void setPixmap(const QPixmap &newPixmap){
        m_pixmapItem->setPixmap(newPixmap);
        fitInView(m_pixmapItem, Qt::KeepAspectRatio);
    }
protected:
    void resizeEvent(QResizeEvent *event){
        QGraphicsView::resizeEvent(event);
        fitInView(m_pixmapItem, Qt::KeepAspectRatio);
    }
private:
    QGraphicsPixmapItem *m_pixmapItem;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QPixmap pixmap(100, 200);
    pixmap.fill(Qt::green);

    Viewer w;
    w.resize(640, 480);
    w.setPixmap(pixmap);
    w.show();

    return a.exec();
}
  • Related