Qt之主窗口设计——打印文本
printtext.h
#ifndef PRINTTEXT_H #define PRINTTEXT_H #include <QtGui> class PrintText : public QMainWindow { Q_OBJECT public: PrintText(QWidget *parent = 0, Qt::WFlags flags = 0); ~PrintText(); void createActions(); void createMenu(); void createToolBars(); public slots: void sl_Print(); private: QTextEdit *edtText; QAction *printerAction; QMenu *fileMenu; QToolBar *fileToolBar; }; #endif // PRINTTEXT_H
printtext.cpp
#include "printtext.h" #include <QFont> #include <QTextEdit> #include <QPrinter> #include <QTextDocument> #include <QPrintDialog> PrintText::PrintText(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) { QFont f("ZYSong18030",12); setFont(f); setWindowTitle(tr("Printer")); edtText = new QTextEdit(this); setCentralWidget(edtText); createActions(); createMenu(); createToolBars(); QFile file("QPrinter.txt"); if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream textStream(&file); while (!textStream.atEnd()) { edtText->append(textStream.readLine()); } file.close(); } } PrintText::~PrintText() { } void PrintText::sl_Print() { QPrinter printer; QPrintDialog printDlg(&printer,this); if(printDlg.exec()) { QTextDocument *doc = edtText->document(); doc->print(&printer); } } void PrintText::createActions() { //"打印"动作 printerAction = new QAction(QIcon("images/print.png"),tr("print"),this); printerAction->setShortcut(tr("Ctrl+P")); printerAction->setStatusTip(tr("Print Text")); connect(printerAction,SIGNAL(triggered()),this,SLOT(sl_Print())); } void PrintText::createToolBars() { //文件工具栏 fileToolBar = addToolBar("File"); fileToolBar->addAction(printerAction); } void PrintText::createMenu() { //文件菜单 fileMenu = menuBar()->addMenu("File"); fileMenu->addAction(printerAction); }
作者:韩兆新
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。