Tuesday, June 7, 2011

Show QImage in a QLabel

QImage enables to construct images from file paths on the disk. Constructed QImages can be displayed in a QLabel. By setting the pixmap value of QLabel from setPixmap function, QLabel displays content of QImage.
Sample project started as a QT Gui Application and contains main.cpp, ShowQImageDialog.h and ShowQImageDialog.cpp files.
ShowQImageDialog constructor creates a QGridLayout instance that is containing a QScrollArea inside it and displays the image in this area.
Project Directory Structure in Qt Creator IDE :


ShowQImageDialog.pro is the project configuration file and contains:
TARGET = ShowQImageDialog
CONFIG   += core gui
TEMPLATE = app
SOURCES += main.cpp \
    ShowQImageDialog.cpp
HEADERS += \
    ShowQImageDialog.h

main.cpp file contains the custom QDialog instance and shows it.
#include <QApplication>
#include "ShowQImageDialog.h"
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    ShowQImageDialog w;
    w.show();
    return a.exec();
}

ShowQImageDialog.h file is the extended QDialog class header file.
#ifndef SHOWQIMAGEDIALOG_H
#define SHOWQIMAGEDIALOG_H
#include <QDialog>
#include <QGridLayout>
#include <QScrollArea>
#include <QLabel>
#include <QImage>

class ShowQImageDialog : public QDialog
{
    Q_OBJECT

public:
    ShowQImageDialog(QWidget *parent = 0);
    ~ShowQImageDialog();
private:
    QGridLayout* gridLayout;
    QImage* inputImg;
    QLabel* imgDisplayLabel;
    QScrollArea* scrollArea;
};

#endif // SHOWQIMAGEDIALOG_H

ShowQImageDialog.cpp file contains implementation details for extended QDialog class.
#include "ShowQImageDialog.h"
ShowQImageDialog::ShowQImageDialog(QWidget *parent) : QDialog(parent)
{
    gridLayout = new QGridLayout();
    inputImg = new QImage("/home/tufan/wallpaper.png");
    imgDisplayLabel = new QLabel("");
    imgDisplayLabel->setPixmap(QPixmap::fromImage(*inputImg));
    imgDisplayLabel->adjustSize();
    scrollArea = new QScrollArea();
    scrollArea->setWidget(imgDisplayLabel);
    scrollArea->setMinimumSize(256,256);
    scrollArea->setMaximumSize(512,512);
    gridLayout->addWidget(scrollArea,0,0);
    setLayout(gridLayout);
}

ShowQImageDialog::~ShowQImageDialog()
{
    delete inputImg;
    delete imgDisplayLabel;
    delete scrollArea;
    delete gridLayout;
}

ShowQImageDialog:

Application created by QT Creator and uses Qt4.7 .

No comments:

Post a Comment