feisky

云计算、虚拟化与Linux技术笔记
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Qt打开并显示图像

Posted on 2010-01-24 14:34  feisky  阅读(3301)  评论(7编辑  收藏  举报
imagewidget.h

 

#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 
 
 
imagewidget.cpp
#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(); 
 } 
 
无觅相关文章插件,快速提升流量