Fork me on GitHub

Qt之主窗口设计——打印文本

image

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);
}
posted @ 2012-11-24 21:15  韩兆新  阅读(1724)  评论(0编辑  收藏  举报