I'm trying to print QTableWidget as pdf in PyQt5, but i'm getting this glitch

298 Views Asked by At

While trying to print QTableWidget I'm getting this glitch where last row is inserted into last column of the 2nd last row, I don't know why is this happening.

I tried a lot of solutions but nothing worked.

Here is the code:

    document = QTextDocument()
    cursor = QTextCursor(document)
    table = cursor.insertTable(
        self.students_reports_table.rowCount(), self.students_reports_table.columnCount())
    for col in range(table.columns()):
        cursor.insertText(self.students_reports_table.horizontalHeaderItem(col).text())
        cursor.movePosition(QTextCursor.NextCell)


    for row in range(table.rows()):
        for col in range(table.columns()):
            cursor.insertText(self.students_reports_table.item(row, col).text())
            cursor.movePosition(QTextCursor.NextCell)
    document.print_(printer)

And here is the output. As you can see clearly in this image last row is in last column of 2nd row:

enter image description here

1

There are 1 best solutions below

3
Alexander On

In your code you create the table with a same amount of rows that in your table widget. Then you immediately fill one of those rows with the header labels. So when you go to fill in the table with data from the widget, there is one less row than needed to fit all the data.

Try setting up the table with students_reports_table.rowCount() + 1.

table = cursor.insertTable(
    self.students_reports_table.rowCount() + 1,  # use rowCount + 1
    self.students_reports_table.columnCount()
)