QTextEdit和QPrintPreview使用大型HTML表格

时间:2018-02-07 13:31:22

标签: python performance pyqt qtextedit qprinter

我正在尝试创建像MS Access这样的报告,并且感谢QTextEdit示例,一切都运行得非常好。但是当我打开一个大的HTML表(大约5000行)时,加载表大约需要35秒 - 所以它非常慢。如何优化打印预览?也许只加载一页并更改打印预览窗口中的当前页面?但我无法找到如何访问打印预览按钮。或者用HTML表格改变一些东西?

#!/usr/bin/env python
import sys
from PyQt4 import QtCore, QtGui

class TextEdit(QtGui.QMainWindow):
    def __init__(self, fileName=None, parent=None):
        super(TextEdit, self).__init__(parent)

        self.setupFileActions()
        self.textEdit = QtGui.QTextEdit(self)
        self.setCentralWidget(self.textEdit)

        if fileName is None:
            fileName = './test5000.htm'
            self.load(fileName)

    def load(self, f):
        if not QtCore.QFile.exists(f):
            return False

        fh = QtCore.QFile(f)
        if not fh.open(QtCore.QFile.ReadOnly):
            return False

        data = fh.readAll()
        codec = QtCore.QTextCodec.codecForHtml(data)
        unistr = codec.toUnicode(data)

        if QtCore.Qt.mightBeRichText(unistr):
            self.textEdit.setHtml(unistr)
        else:
            self.textEdit.setPlainText(unistr)
        return True

    def setupFileActions(self):
        menu = QtGui.QMenu("&File", self)
        self.menuBar().addMenu(menu)

        self.actionOpen = QtGui.QAction(
            QtGui.QIcon.fromTheme('document-open'),
            "&Open...", self, shortcut=QtGui.QKeySequence.Open,
            triggered=self.fileOpen)
        menu.addAction(self.actionOpen)
        menu.addSeparator()

        self.actionPrintPreview = QtGui.QAction(
            QtGui.QIcon.fromTheme('fileprint'),
            "Print Preview...", self,
            shortcut=QtCore.Qt.CTRL + QtCore.Qt.SHIFT + QtCore.Qt.Key_P,
            triggered=self.filePrintPreview)
        menu.addAction(self.actionPrintPreview)

    def fileOpen(self):
        fn = QtGui.QFileDialog.getOpenFileName(self, "Open File...", "C:",
                                           "HTML-Files (*.htm *.html);;All Files (*)")
        if fn:
            self.load(fn)

    def filePrintPreview(self):
        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)

        printer.setOrientation(1)
        printer.setPageSize(8)
        printer.setPageMargins(20, 20, 20, 20, 0)
        printer.setResolution(300)

        preview = QtGui.QPrintPreviewDialog(printer, self)
        preview.paintRequested.connect(self.printPreview)
        preview.exec_()

    def printPreview(self, printer):
        self.textEdit.print_(printer)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    mainWindows = []
    for fn in sys.argv[1:] or [None]:
        textEdit = TextEdit(fn)
        textEdit.resize(1024, 768)
        textEdit.show()
        mainWindows.append(textEdit)

    sys.exit(app.exec_())

包含图片的示例HTML文件为here

当您运行脚本时,它会(慢慢地)打开HTML文件,然后菜单文件 - >打印预览会运行打印预览对话框。

0 个答案:

没有答案