QT自定义UI组件_图片倒影

实现思想:

  两张相同的图片上下对立显示, 上下两张他模糊度不同

示例1

如下图:

  

代码如下:

class ShowWidget : public QWidget
{
    Q_OBJECT

public:
    ShowWidget(QString imgPaht, QWidget *parent = nullptr);
    ~ShowWidget();
    void paintEvent(QPaintEvent *event);
    void InitWidget();
private:
    QLabel* m_ImgLab;
    QLabel* m_InvertedImgLab;
    QVBoxLayout* m_MainLayout;
private:
    QString m_ImgPath;
private:
    Ui::ShowWidget *ui;
};

  cpp文件: 用到了QImage中的mirrored(bool, bool), 参数1:是否水平翻转, 参数二: 是否垂直翻转

ShowWidget::ShowWidget(QString imgPath, QWidget *parent) : QWidget(parent), ui(new Ui::ShowWidget)
{
    m_ImgPath = imgPath;
    InitWidget();
    ui->setupUi(this);
}

ShowWidget::~ShowWidget()
{
    delete ui;
}

void ShowWidget::paintEvent(QPaintEvent *event)
{
    //设置背景图片
    QPalette pal(this->palette());
    pal.setColor(QPalette::Background, Qt::green);
    this->setAutoFillBackground(true);
    this->setPalette(pal);
}

void ShowWidget::InitWidget()
{
    m_MainLayout = new QVBoxLayout;
    m_ImgLab = new QLabel;
    m_InvertedImgLab = new QLabel;
    //设置倒影高度:原图高度 = 2:3
    m_InvertedImgLab->resize(m_ImgLab->width(), m_ImgLab->height() / 3 *2);

    QPixmap pixmap(m_ImgPath);
    pixmap = pixmap.scaled(m_ImgLab->size(), Qt::IgnoreAspectRatio);
    m_ImgLab->setPixmap(pixmap);

    QImage inertedImg(m_ImgPath);
    //绘制倒影图片的模糊度
    QPainter painter;
    painter.begin(&inertedImg);
    painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
    painter.fillRect(inertedImg.rect(), QColor(0,0,0,80));
    painter.end();

    //垂直翻转
    inertedImg = inertedImg.mirrored(false, true);
    pixmap = QPixmap::fromImage(inertedImg);
    pixmap = pixmap.scaled(m_InvertedImgLab->size(), Qt::IgnoreAspectRatio);
    m_InvertedImgLab->setPixmap(pixmap);
    m_MainLayout->setContentsMargins(50, 0,50,0);
    m_MainLayout->setSpacing(0);
    m_MainLayout->addStretch(1);
    m_MainLayout->addWidget(m_ImgLab, 1, Qt::AlignCenter);
    m_MainLayout->addWidget(m_InvertedImgLab, 1, Qt::AlignCenter);
    m_MainLayout->addStretch(1);
    this->setLayout(m_MainLayout);
}

  

示例2:全部在QPainterEvent中完成绘制

如下图

 

 代码如下

void SelfLabel::paintEvent(QPaintEvent * paint)
{
    Q_UNUSED(paint)
    QPainter painter(this);
    QPixmap pix;
    pix.load(":/image/img11.jpg");
    //坐标系平移
    painter.translate(150,150);
    //在widget绘制图片
    painter.drawPixmap(200,0,600,400,pix);
    painter.shear(-0.9,0.0);  //纵向扭曲
    //设置倒影透明度
    painter.setOpacity(0.3);
    QImage img(":/image/img11.jpg");
    img = img.mirrored(false, true);
    pix= QPixmap::fromImage(img);
    painter.drawPixmap(560,400,600,200,pix);
}

  

 

posted @ 2020-07-30 15:02  Software_hul  阅读(469)  评论(0编辑  收藏  举报