我敢肯定你想實現一切皆有可能使用PyQt4的。
我已經在下面添加了一個基本腳本,演示了您之後的功能。打印的表格格式非常粗糙,但通過使用html而不是使用簡單的文本表,您可以輕鬆獲得更好的效果。
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setWindowTitle(self.tr('Document Printer'))
self.table = QtGui.QTableWidget(200, 5, self)
for row in range(self.table.rowCount()):
for col in range(self.table.columnCount()):
item = QtGui.QTableWidgetItem('(%d, %d)' % (row, col))
item.setTextAlignment(QtCore.Qt.AlignCenter)
self.table.setItem(row, col, item)
self.table.setHorizontalHeaderLabels(
'SKU #|NAME|DESCRIPTION|QUANTITY|PRICE'.split('|'))
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 = QtGui.QGridLayout(self)
layout.addWidget(self.table, 0, 0, 1, 2)
layout.addWidget(self.buttonPrint, 1, 0)
layout.addWidget(self.buttonPreview, 1, 1)
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_()
def handlePaintRequest(self, printer):
document = QtGui.QTextDocument()
cursor = QtGui.QTextCursor(document)
table = cursor.insertTable(
self.table.rowCount(), self.table.columnCount())
for row in range(table.rows()):
for col in range(table.columns()):
cursor.insertText(self.table.item(row, col).text())
cursor.movePosition(QtGui.QTextCursor.NextCell)
document.print_(printer)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())