【问题标题】:Converting SQL data into a QTextDocument and then outputting a pdf将SQL数据转换成QTextDocument,然后输出pdf
【发布时间】:2014-02-08 17:24:58
【问题描述】:

我正在尝试添加一种将 sqlite3 数据库中的数据导出到 pdf 文档的方法。在《使用 python 和 Qt 进行快速 gui 编程》一书中,它说我可以将 QTextDocuments 导出为 pdf 文件。但是它需要采用 QTextDocument 的形式。目前,我一直在尝试将表格的标题字符串作为测试放入 pdf 文档中,但是当它空闲运行时,它会重新启动。

    import sqlite3
    from PyQt5 import QtWidgets, QtCore, QtGui
    class Report(QtWidgets.QWidget):
        def __init__(self,text):
            super(Report,self).__init__()
            self.textArea = QTextEdit(self)
            self.cursor = QTextCursor(self.textArea.document())
            self.cursor.insertText(text)

    def createTextReport(fileName):
        headings = ('|%10s|'%'AssetID' + '|%40s|'%'Description' + '|%40s|'%'Room Description' + '|%5s|'%'Labelled' + '|%10s|'%'Condition')
        report = Report(headings)
        printer = QPrinter()
        printer.setPageSize(QPrinter.Letter)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName('C:/Users/Luke/Documents/A-Level-Work/A2/Computing/COMP 4/Program/report.pdf')
        report.print_(printer)


    fileName = 'C:/Users/Luke/Documents/A-Level-Work/A2/Computing/COMP 4/Program/test_database.db'

    createTextReport(fileName)

我想知道我哪里出错了,还有一种简单的方法可以将 SQL 查询中的数据转换为 QTextDocument 格式的表格,因此我不必手动对其进行格式化。由于我的编程知识非常有限,请简单解释一下。

【问题讨论】:

  • 哪里出了问题?代码是否运行?您需要有关如何构建数据的指示吗?
  • 代码运行,但是当它到达 createTextReport(fileName) 时空闲重新启动而没有提供错误。我想知道是否有一些模块可以将 SQL 转换为 QTextDocument。
  • 如果有人问没有文件被创建。
  • 由于 Qt 是一个相当紧密耦合的系统,您可能必须先创建一个正在运行的QApplication,然后才能使用它的一些库。这很愚蠢,但这可能是问题所在。

标签: python sqlite python-3.x pyqt pyqt5


【解决方案1】:

如果您只有来自 sqlite3 模块的元组,那么您可以使用以下方式格式化您的数据:

myText = ''

for entry in conn.execute('SOME SQL QUERY'):
    myText += '|{:10s}| AssetID |{:40s}| Description |{:40s}| Room Description |{:5s}| Labelled |{:10s}| Condition'.format(*entry)
    myText += '\n'

然后您可以将此文本输入到您的 Report() 对象中。

使用this post

【讨论】:

  • 感谢 SQL 到文本的帮助!您对为什么将文本转为 pdf 的代码部分不起作用有任何想法吗?
  • 我不完全确定。最近有点忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 2019-12-21
  • 1970-01-01
  • 2020-06-28
相关资源
最近更新 更多