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):
		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

if __name__=="__main__":
	app = QApplication(sys.argv)
	myurl = ""
	widget = htmlViewer(myurl)

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 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()

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.