posted on: 2008-09-26 07:39:24
This is two techniques to get to print.

>This is Qt programming at its most basic. Original problem, I have a QWebView and I want to print it. DO NOT follow the exact syntax from riverbankRiverbank Computing word for word. This is how you should do it if you want it quickly and effectively, I am following their guidlines using signals and slots.

#!/usr/bin/env python

"""
Lets get the print thing working
"""
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import PyQt4.QtWebKit as QtWebKit

import sys

class htmlViewer(QtWebKit.QWebView):
	def __init__(self,url, parent=None):
		QtWebKit.QWebView.__init__(self,parent)
		self.setUrl(QUrl(url))
		self.preview = QPrintPreviewDialog()
		self.connect(self.preview,SIGNAL("paintRequested (QPrinter *)"),SLOT("print (QPrinter *)"))
		self.connect(self,SIGNAL("loadFinished (bool)"),self.execpreview)
	def execpreview(self,arg):
		print arg
		self.preview.exec_()

if __name__=="__main__":
	app = QApplication(sys.argv)
	
	myurl = "http://www.google.com"
	widget = htmlViewer(myurl)
	widget.show()
		
	sys.exit(app.exec_())

So I have two signals, the first one is a pain, I think I would have saved myself a lot of trouble if I had never tried to put "void" near the SIGNAL calls. Anyway, the QPrintPreviewDialog will emit the "paintRequest()" signal twice. The first time it emits it a preview is made the second time it emits the QWebView uses its print command with the QPrintPreviewDialog printer which knows to print this time.

No lets say I wanted to have the file print without a print slot. This is important because it introduces the use of a QPainter() for this example my paint device is a printer but the paint device could be a QWidget such as a QPixmap. This file actually uses the whole example you can use it to print images qt_print.py and here is the function I used to replace the print() slot.

#new connect statement
self.connect(self.preview,SIGNAL("paintRequested (QPrinter *)"),self.what)
#new 'print' function
def what(self,printer):
	painter = QPainter()
	painter.begin(other)
	self.mylabel.render(painter)
	painter.end()

Also if you do not want to use the QPrintPreviewDialog then you could just send a printer to that function.

Lastely, the QPrintPreviewDialog does not display images properly unless the scale is 100%, but it prints fine.

Comments

Name: