카테고리 없음

QPainter Class 와 Graphics

디해가태구디 2023. 4. 25. 09:10

1. header파일에 protected virtual void paintEvent 를 선언한다. 

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>



QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget

{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

protected:
    virtual void paintEvent(QPaintEvent *event);


private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

 

2. 프로젝트 파일에 Add new를 하고 Resource파일을 Add한다. 

 

3. widget.cpp 파일에 높이, 비율 설정, 배경색깔등을 설정한다. 

#include "widget.h"
#include "ui_widget.h"
#include <QPainter>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter;
    painter.begin(this);


    int w = this ->window() -> width();
    int h = this ->window() ->height();

    QPixmap imgPixmap = QPixmap(":/images/image.jpg").scaled(w, h, Qt::KeepAspectRatio);

    painter.setPen(QColor(0,0,0));
    painter.fillRect(0,0,w,h,Qt::black);

    int xPos = 0;
    int yPos = 0;

    if( w> imgPixmap.width())
        xPos = ( w- imgPixmap.width()) / 2; //가로 크기가 이미지보다 클 경우
    else if( h > imgPixmap.height())
        xPos = (h - imgPixmap.height())/2;

    painter.drawPixmap(xPos, yPos, imgPixmap);

    painter.end();
}

Widget::~Widget()
{
}

Qt::KeepAspectRatio 를 사용하면 화면 크기에 맞게 이미지가 비율에 맞춰진다.