Qt之主窗口设计——打印图像
printimage.h
#ifndef PRINTIMAGE_H #define PRINTIMAGE_H #include <QtGui> #include <QImage> class PrintImage : public QMainWindow { Q_OBJECT public: PrintImage(QWidget *parent = 0, Qt::WFlags flags = 0); ~PrintImage(); void createActions(); void createMenus(); void createToolBars(); public slots: void sl_print(); private: QLabel *labImage; QImage image; QAction *printAction; QMenu *fileMenu; QToolBar *fileToolBar; }; #endif // PRINTIMAGE_H
printimage.cpp
#include "printimage.h" PrintImage::PrintImage(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) { setWindowTitle(tr("PrintImage")); labImage = new QLabel(this); labImage->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored); labImage->setScaledContents(true); setCentralWidget(labImage); createActions(); createMenus(); createToolBars(); if(image.load("tux.png")) { labImage->setPixmap(QPixmap::fromImage(image)); resize(image.width(),image.height()); } } PrintImage::~PrintImage() { } void PrintImage::createActions() { printAction = new QAction(QIcon("images/print.png"),tr("Print"),this); printAction->setShortcut(tr("Ctrl+P")); printAction->setStatusTip(tr("Print Image")); connect(printAction,SIGNAL(triggered()),this,SLOT(sl_print())); } void PrintImage::createMenus() { fileMenu = menuBar()->addMenu(tr("File")); fileMenu->addAction(printAction); } void PrintImage::createToolBars() { fileToolBar = addToolBar("File"); fileToolBar->addAction(printAction); } void PrintImage::sl_print() { QPrinter printer; QPrintDialog printDlg(&printer,this); if(printDlg.exec()) { QPainter painter(&printer); QRect rect = painter.viewport(); QSize size = image.size(); size.scale(rect.size(),Qt::KeepAspectRatio); painter.setViewport(rect.x(),rect.y(),size.width(),size.height()); painter.setWindow(image.rect()); painter.drawImage(0,0,image); } }
作者:韩兆新
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。