printer.pro
#-------------------------------------------------
#
# Project created by QtCreator 2012-04-10T16:12:44
#
#-------------------------------------------------
QT += core gui widgets printsupport
TARGET = printer
TEMPLATE = app
SOURCES += main.cpp\
widget.cpp \
myprinter.cpp
HEADERS += widget.h \
myprinter.h
FORMS += widget.ui \
myprinter.ui
myprinter.h
#ifndef MYPRINTER_H
#define MYPRINTER_H
#include <QDialog>
namespace Ui {
class myPrinter;
}
class myPrinter : public QDialog
{
Q_OBJECT
public:
explicit myPrinter(QWidget *parent = 0);
~myPrinter();
private:
Ui::myPrinter *ui;
};
#endif // MYPRINTER_H
myprinter.cpp
#include "myprinter.h"
#include "ui_myprinter.h"
myPrinter::myPrinter(QWidget *parent) :
QDialog(parent),
ui(new Ui::myPrinter)
{
ui->setupUi(this);
}
myPrinter::~myPrinter()
{
delete ui;
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPrinter>
#include "myprinter.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void printImage();
private slots:
void on_pushButton_clicked();
void plotPic(QPrinter *);
private:
Ui::Widget *ui;
myPrinter * myprinter;
QPrinter *printer;
// QPrinter printer;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QPrintDialog>
#include <QTableWidget>
#include <QPainter>
#include <QPrintPreviewDialog>
#include <QMessageBox>
#include <QDialog>
#include <QtDebug>
#include <QTextDocument>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
myprinter = new myPrinter(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
QPrinter printer(QPrinter::HighResolution);
QPrintPreviewDialog preview(&printer,0);/* 打印预览 */
/**
* QPrintPreviewDialog类提供了一个打印预览对话框,里面功能比较全,
* paintRequested(QPrinter *printer)是系统提供的,
* 当preview.exec()执行时该信号被触发,
* plotPic(QPrinter *printer)是用户自定义的槽函数,图像的绘制就在这个函数里。
*/
connect(&preview, SIGNAL(paintRequested(QPrinter *)),this,SLOT(plotPic(QPrinter *)));
this->close();
preview.exec(); /* 等待预览界面退出 */
}
void Widget::plotPic(QPrinter *printer)
{
QDialog *myForm = myprinter;
QPainter painter(printer);
QPixmap image;
image=image.grabWidget(myForm,0,0,400,300);/* 绘制窗口至画布 */
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.drawPixmap(0,0,image);/* 数据显示至预览界面 */
}
main.cpp
#include <Qapplication>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
myprinter.ui 是需要答应的内容可以随便添加内容