首先,设置工程文件:QT += printsupport
打印图像实际实在一个QPaintDevice中画图。打印创建QPrinter对象进行画图,QPrinter本质上也是一个绘图设备QPaintDevice。
~~~~~上代码~~~~
pic_widget.h
#ifndef PICWIDGET_H #define PICWIDGET_H #include <QPainter> #include <QWidget> #include <QPushButton> #include <QPrintDialog> #include <QPrinter> #include <QPainter> #include <QRect> #include <QImage> class PicWidget : public QWidget { Q_OBJECT public: explicit PicWidget(QWidget *parent = 0); public slots: void slotPrintPic(); private: QPushButton *pintPicBtn; QImage img; }; #endif //--PICWIDGET_Hpic_widget.cpp
#include "pic_widget.h" PicWidget::PicWidget(QWidget *parent /*= 0*/) : QWidget(parent) { //---按钮 pintPicBtn = new QPushButton("print", this); pintPicBtn->setGeometry(70, 40, 50, 30); connect(pintPicBtn, SIGNAL(clicked()), this, SLOT(slotPrintPic())); //--导入图片 img.load(":/1"); //---窗口属性 resize(200, 100); } //---按钮槽函数 void PicWidget::slotPrintPic() { QPrinter printer; //---构建新对象 QPrintDialog printDlg(&printer, this); if (printDlg.exec()) // 用于判断用户是否点击“打印”按钮 { QPainter painter(&printer); QRect rect = painter.viewport(); //---获取Qpainter对象的矩形区域 QSize size = img.size(); //--获取图片的大小 size.scale(rect.size(), Qt :: KeepAspectRatio); //----按照图形比例大小重新设置视口矩形区域 //---打印图片 painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); painter.setWindow(img.rect()); painter.drawImage(0, 0, img); } }main.cpp
#include <QtWidgets/QApplication> #include "pic_widget.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); PicWidget win; win.show(); return a.exec(); }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~