python-3.xpyqt5qtextdocumentqtextcursor

Python Adding Pictures and headers to QPrintWidget


How can I add a header and a picture to my QPrintWidget /Printout ?

I found this really nice looking layouted outputfile. I would love to make my file look somthing like that. I tried to find a tutorial explaining how to do the 'layouting' of a file, but could not find any.

I would be really glad about some suggestions/help.

So far this is mycode, where the table is beeing drawn from the QTableWidget:

 def handlePaintRequest(self, printer):
        document = QtGui.QTextDocument()
        cursor = QtGui.QTextCursor(document)

        table = cursor.insertTable(self.table.rowCount(), self.table.columnCount())

        for row in range(table.rows()):
            for col in range(table.columns()):
                it = self.table.item(row, col)
                if it is not None:
                    cursor.insertText(it.text())
                cursor.movePosition(QtGui.QTextCursor.NextCell)
        document.print_(printer)

enter image description here


Solution

  • My answer is based on the above link which you are refering to.... I would just show you how to add header.. I am not changing the current solution, just give you a possible solution....

    def paintPage(pageNumber, pageCount, painter, doc, textRect, footerHeight):
    
        .......................
    
        headerRect = QtCore.QRectF(textRect)
        headerRect.setTop(textRect.top())
        headerRect.setHeight(2*footerHeight)
    
        .......................
    
    painter.drawText(footerRect, QtCore.Qt.AlignCenter, "Page {} of {}".format(pageNumber+1, pageCount))
    painter.drawText(headerRect, QtCore.Qt.AlignLeft, "{}\n{}".format('Project name:', 'Project number:'))