简体   繁体   English

在QTableWidget中如何打印数据库中的数据?

[英]How can I print data from my database while in QTableWidget?

How can I print my data from my database (sqlite) into a notepad /word document from my table in my GUI (using the same formatting). 如何将数据库(sqlite)中的数据打印到GUI中的表中的记事本/ word文档中(使用相同的格式)。 Here is my code for the table which is represented on my gui. 这是我的GUI上代表的表的代码。

class Table(QtGui.QDialog):
    def __init__(self):
        super(Table, self).__init__()
        with sqlite3.connect('database.db') as db:
            cursor=db.cursor()
            cursor.execute('select* from Receipt Order BY ReceiptID ASC')
            title = [cn[0] for cn in cursor.description]
            rows = [cn[0] for cn in cursor.description]
            cur=cursor.fetchall()
            layout = QtGui.QGridLayout() 
            self.table = QtGui.QTableWidget()
            self.setGeometry(500,500,500,400)
            qr = self.frameGeometry()
            cp = QtGui.QDesktopWidget().availableGeometry().center()
            qr.moveCenter(cp)
            self.move(qr.topLeft())
            self.label2=QtGui.QLabel(self)
            self.label2.setPixmap(QtGui.QPixmap('receipt_pic.jpg'))
            self.label2.setGeometry(0,0,500,400)
            self.table.setColumnCount(2)
            self.table.setHorizontalHeaderLabels(title)
            for i,row in enumerate(cur):
                self.table.insertRow(self.table.rowCount())
                for j,val in enumerate(row):
                    self.table.setItem(i, j, QtGui.QTableWidgetItem(str(val)))
            layout.addWidget(self.table, 0, 0)
            self.setLayout(layout)
            self.setWindowTitle('Receipt Table')

I want to be able to click a button which copies this information (which would appear as a table with filled columns and rows) into a seperate notepad file / or any text document (where I can send the table to the printer to be printed). 我希望能够单击一个按钮,将此信息(将显示为具有填充的行和列的表)复制到单独的记事本文件或任何文本文档中(可以将表发送到要打印的打印机) 。

It would probably be easier to just print the table directly, rather than use an intermediary file. 直接打印表而不是使用中间文件可能会更容易。

To do this, you can use a QTextDocument to create a printable representation of the table, and then use the built-in print dialogs to do the rest. 为此,可以使用QTextDocument创建表的可打印表示形式,然后使用内置的打印对话框来完成其余操作。

So, first add some buttons: 因此,首先添加一些按钮:

    ...
    layout.addWidget(self.table, 0, 0, 1, 2)
    self.buttonPrint = QtGui.QPushButton('Print', self)
    self.buttonPrint.clicked.connect(self.handlePrint)
    self.buttonPreview = QtGui.QPushButton('Preview', self)
    self.buttonPreview.clicked.connect(self.handlePreview)
    layout.addWidget(self.buttonPrint, 1, 0)
    layout.addWidget(self.buttonPreview, 1, 1)
    self.setLayout(layout)
    ...

then some handlers for the print and print-preview dialogs: 然后是一些用于打印和打印预览对话框的处理程序:

def handlePrint(self):
    dialog = QtGui.QPrintDialog()
    if dialog.exec_() == QtGui.QDialog.Accepted:
        self.handlePaintRequest(dialog.printer())

def handlePreview(self):
    dialog = QtGui.QPrintPreviewDialog()
    dialog.paintRequested.connect(self.handlePaintRequest)
    dialog.exec_()

and finally some methods for creating the document and printing it: 最后是创建和打印文档的一些方法:

def handlePaintRequest(self, printer):
    document = self.makeTableDocument()
    document.print_(printer)

def makeTableDocument(self):
    document = QtGui.QTextDocument()
    cursor = QtGui.QTextCursor(document)
    rows = self.table.rowCount()
    columns = self.table.columnCount()
    table = cursor.insertTable(rows + 1, columns)
    format = table.format()
    format.setHeaderRowCount(1)
    table.setFormat(format)
    format = cursor.blockCharFormat()
    format.setFontWeight(QtGui.QFont.Bold)
    for column in range(columns):
        cursor.setCharFormat(format)
        cursor.insertText(
            self.table.horizontalHeaderItem(column).text())
        cursor.movePosition(QtGui.QTextCursor.NextCell)
    for row in range(rows):
        for column in range(columns):
            cursor.insertText(
                self.table.item(row, column).text())
            cursor.movePosition(QtGui.QTextCursor.NextCell)
    return document

If you prefer to save to a file, you can use QTextDocument.toHtml to dump the table as html. 如果您喜欢保存到文件,则可以使用QTextDocument.toHtml将表转储为html。

The printed results are quite basic, but if you want something more fancy, you can always build the document using html/css. 打印的结果是非常基本的,但是如果您想得到更多效果,可以始终使用html / css来构建文档。

I use this function 我用这个功能

    def LoadDatabase(self):
        self.banco = sqlite3.connect ( 'Vendas.db' )
        self.cursor = banco.cursor ( )
        query = "SELECT * FROM Produtos"
        result = self.banco.execute ( query )
        self.listaprodutos.setRowCount ( 0 )
        for row_number, row_data in enumerate ( result ):
            self.listaprodutos.insertRow ( row_number )
            for colum_number, data in enumerate ( row_data ):
                self.listaprodutos.setItem ( row_number, colum_number, QtWidgets.QTableWidgetItem ( str ( data ) ) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM