IDE/QT Creator

[QT5] 새 위젯창에서 이미지 띄우기(QWidget, QImage)

쩡 (개발꿈나무) 2021. 1. 11. 16:45

* 개인 공부 환경에서 기록 용도로 작성된 글입니다.

 

pro랑 main 파일은 변경없음

protoserial.h

#ifndef PROTOSERIAL_H
#define PROTOSERIAL_H

#include <QMainWindow>
#include <QString>
#include <QImage>
#include <QPixmap>
#include <QLabel>
#include <QMessageBox>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QVideoWidget>

QT_BEGIN_NAMESPACE
namespace Ui { class ProtoSerial; }
QT_END_NAMESPACE

class ProtoSerial : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_btn_go_clicked();
    void on_btn_stop_clicked();

    QImage CreateTestData();
    void CreateWidget(QImage _data);
    void DisplayImage(QWidget *_widg, QImage _img);

private:
    Ui::ProtoSerial *ui;
};
#endif // PROTOSERIAL_H

 

protoserial.cpp

#include "protoserial.h"
#include "ui_protoserial.h"


ProtoSerial::ProtoSerial(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::ProtoSerial)
{
    ui->setupUi(this);
    this->setFixedSize(800,400);
}

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


// [signals] -------------------------------
// :get serial


// [slots] ---------------------------------
void ProtoSerial::on_btn_go_clicked()
{
    QImage data;

    data = CreateTestData();

    CreateWidget(data);
}

void ProtoSerial::on_btn_stop_clicked()
{
    // stop while
}



// [method] --------------------------------
QImage ProtoSerial::CreateTestData()
{
    QImage *img = new QImage();
    img->load("/home/jjung/vongole.jpg");
//    if(*_img) { // :load image }
//    else      { QMessageBox::about(0, QString::fromAscii_helper("Image load error.", -1), QString::fromAscii_helper("Image load error.", -1)); }

    return *img;
}

void ProtoSerial::CreateWidget(QImage _data)
{
    QWidget *widg = new QWidget();

    widg->setFixedSize(this->width(), this->height());
    DisplayImage(widg, _data);
    widg->show();
}

void ProtoSerial::DisplayImage(QWidget *_widg, QImage _img)
{
    QPixmap *buf = new QPixmap();
    QLabel *lb_img = new QLabel(_widg);	// 라벨(this) 해주고, 위젯->show를 없애주면 기존창에서 전체화면된 결과가 나온다. 

    *buf = QPixmap::fromImage(_img);
    *buf = buf->scaled(_widg->width(), _widg->height());

    lb_img->setPixmap(*buf);
    lb_img->resize(buf->width(),buf->height());
    lb_img->move(0,0);

    lb_img->show();
}

 

결과

실행직후
go버튼 클릭직후