1

我正在尝试创建像 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 文件在这里

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

4

0 回答 0