#ifndef IMAGEWIDGET_H #define IMAGEWIDGET_H #include <QWidget> #include <QImage> #include <QPainter> #include <QString> #include <QFileDialog> #include <QMessageBox> #include <QPushButton> class ImageWidget : public QWidget { Q_OBJECT public: ImageWidget(); /* The QImage class provides a hardware-independent image representation that allows direct access to the pixel data, and can be used as a paint device. Qt provides four classes for handling image data: QImage, QPixmap, QBitmap and QPicture. QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen. QBitmap is only a convenience class that inherits QPixmap, ensuring a depth of 1. Finally, the QPicture class is a paint device that records and replays QPainter commands. */ QImage img; protected: void paintEvent(QPaintEvent*); private: QPushButton *openButton; public slots: void openImage(); }; #endif // IMAGEWIDGET_H
#include "imagewidget.h" ImageWidget::ImageWidget() { openButton=new QPushButton(tr("Open Image"),this); //openButton->setGeometry(50,50,50,100); connect(openButton,SIGNAL(clicked()),this,SLOT(openImage())); openButton->show(); } void ImageWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); if(!img.isNull()) painter.drawImage(0,0,img); //img.save("test.bmp"); } void ImageWidget::openImage() { QString filename=QFileDialog::getOpenFileName(this, tr("Open Image"),"", tr("BMP(*.bmp);;JPG(*.jpg);;ALL files(*.*)")); if(filename.isEmpty()) { QMessageBox::information(this,tr("Open Image"), tr("Please select an image to open")); filename=QFileDialog::getOpenFileName(this, tr("Open Image"),"", tr("BMP(*.bmp);;JPG(*.jpg);;ALL files(*.*)")); } if(!(img.load(filename,0))) { QMessageBox::information(this,tr("Unable to open the Image"), tr("Please select a valid image.")); return; } QWidget::update(); }