pythonpyqt5qprinterqdatetime

convert to date format in pyqt5 Qprinter


Is there a way to convert to date format will use the Printer and QTextDocument the result always show in the date and time like in the image?

this is my code

def handlePaintRequest(self, printer):

        model_hjd = QSqlTableModel()
        model_hjd.setTable('transactions')
       
        date = str(self.dateEdit_10.text())
        date_2 = str(self.dateEdit_14.text())

        self.tableView_22.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        model_hjd.setSort(6, Qt.DescendingOrder)
        self.tableView_22.setModel(model_hjd)
        model_hjd.select()
        filter_ft = "date_d BETWEEN '%s' AND '%s'" % (date, date_2)
        model_hjd.setFilter(filter_ft)

        self.tableView_22.setModel(model_hjd)

        document = QTextDocument()
        cursor = QTextCursor(document)
        tableFormat = QTextTableFormat()
        table = cursor.insertTable(model_hjd.rowCount() + 1, model_hjd.columnCount(), tableFormat)
        myheaders = []
        for i in range(0, model_hjd.columnCount()):
            myheader = model_hjd.headerData(i, Qt.Horizontal)
            cursor.insertText(myheader)
            cursor.movePosition(QTextCursor.NextCell)

        for row in range(0, model_hjd.rowCount()):
           for col in range(0, model_hjd.columnCount()):
               index = model_hjd.index( row, col )
               cursor.insertText(str(index.data()))
               cursor.movePosition(QTextCursor.NextCell)
        document.print_(printer)

but the result in date and time are like this

enter image description here


Solution

  • You could use a custom function to format the different types of data in your table, e.g.

    @staticmethod
    def to_string(entry):
        if isinstance(entry, (QtCore.QDate, QtCore.QTime, QtCore.QDateTime)):
            return entry.toString(Qt.SystemLocaleShortDate)
        else:
            return str(entry)
    
    def handlePaintRequest(self, printer):
        ....
        cursor.insertText(self.to_string(index.data()))
        ....