# -*- coding: utf-8 -*-

    #what i want todo is : show to the user all pages in QPrintPreviewWidget
    #and when he press 'print it' button it prints only the pages from 5 to 7

    #my problem is
    #1- with the two option setPrintRange and setFromTo in method what_to_paint()
    #it still print all the pages and i only want the pages in range(5 to 7)

    #2- another problem but i can go around it why the paintRequested signal emitted after i press 'print it' button
    #what happen is the signal emitted towice one when the program lunch and second when i press print button

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class printall(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setObjectName("printerprinter")
        self.setWindowModality(Qt.WindowModal)
        self.resize(500, 300)

        self.printer=QPrinter(QPrinter.PrinterResolution)
        self.printer.setOrientation(QPrinter.Portrait)
        self.printer.setFullPage(True)
        self.printer.setPageMargins(0, 0, 0, 0, QPrinter.DevicePixel)
        
        self.BOX = QPrintPreviewWidget(self.printer, self)
        self.BOX.setGeometry(QRect(10, 10, 450, 220))
        self.BOX.setObjectName("BOX")
        self.BOX.setZoomFactor(1.0)
        
        btn_print = QPushButton('print it', self)
        btn_print.setGeometry(350, 250, 50, 50)


        self.connect(self.BOX,SIGNAL("paintRequested (QPrinter *)"),self.what_to_paint)
        self.connect(btn_print,SIGNAL("clicked ()"), self.ok_print)
        
        
    def what_to_paint(self,other):#other is the printer object passed when signal paintRequested emitted 
        painter = QPainter()
        painter.begin(other)
        x=1
        while x<10:
            print x
            painter.setFont(QFont('Decorative', 25))    # change font
            text='page : '+str(x)+'\nWelcom'
            painter.drawText(100,100,text)              # printing point
            other.newPage()
            x+=1
        painter.end()

        other.setPrintRange(QPrinter.PageRange)#this supposed to make the printer print the ranged page only
        other.setFromTo(5, 7)#set the ranged page from 5 to 7 
        self.other=other

    def ok_print(self):
        print 'printing now'
        self.BOX.print_()

if __name__ == '__main__':
    app=QApplication(sys.argv)
    myapp=printall()
    myapp.show()
    sys.exit(app.exec_())




