当前位置:网站首页>QT picture adaptive display control

QT picture adaptive display control

2022-06-11 07:28:00 Fantastical Yu ruiyin

Write it at the front

Used to Qt Students who show pictures should find , Configuration is really uncomfortable , Use QLabel The display image is prone to incomplete display of the image or the deformation of the control caused by the large image , Quite uncomfortable . To realize the adaptive display of pictures, you generally need to use painterevent To configure the page , For some beginners, there may be a certain difficulty in configuring , After all, I am divorced from .ui You may not know how to design the page . So here I make a control that can adaptively display pictures , Only need to QWidget Control can be promoted to this control to realize the adaptive display of pictures .

Go straight to the code

The header file

#ifndef MYIMAGE_H
#define MYIMAGE_H

#include <QWidget>
#include <QPainter>
#include <QImage>

// Use painterevent, Let pictures follow widget The size of the self-adaptive adjustment 
class MyImage:public QWidget
{
    
    Q_OBJECT

public:
    explicit MyImage(QWidget *parent = nullptr);
    ~MyImage();
    void setImage(QImage image);
protected:
    void paintEvent(QPaintEvent *);
private:
    QImage image;
};






#endif // MYIMAGE_H

cpp file

#include "myimage.h"

MyImage::MyImage(QWidget *parent)
{
    
    image.load(":/image.png");
}

MyImage::~MyImage()
{
    

}

void MyImage::paintEvent(QPaintEvent *)
{
    
    int width=this->width();
    int height=this->height();

    QPainter painter(this);
    painter.save();
    // Resize the picture to the size of the form 
    image.scaled(width,height);

    // Draw a picture 
    painter.drawImage(this->rect(),image);
    painter.restore();
    painter.setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing);
// painter.translate(width/2,height/2);

    // It can be set as a square , Smallest size bit 200*200;
    int side =qMin(width,height);
    painter.scale(side/200,side/200);
}

void MyImage::setImage(QImage image)
{
    
    this->image=image;
    update();
}

How to use

Add the above two files to the project ( No, .ui file ), Add a... In the display interface QWidget Control , And will QWidget Upgrade to MyImage, You only need to use setImage Function to refresh the image .
 As shown in the figure, the control that displays the picture is promoted to MyImage

According to the effect

 According to the effect

原网站

版权声明
本文为[Fantastical Yu ruiyin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020521151380.html