[英]Insert table into QTextEdit with PyQt4
How can I insert a tabel inside a QTextEdit to be printed on A4 paper. 我如何在要打印在A4纸上的QTextEdit内插入表格。 I wrote this code but I don't know how I can insert it into the value, just insert first cell: 我写了这段代码,但不知道如何将其插入值中,只需插入第一个单元格即可:
self.text = QtGui.QTextEdit()
self.cursor = QtGui.QTextCursor()
self.cursor = self.text.textCursor()
self.cursor.insertTable(2, 5)
self.cursor.insertText("first cell ")
Maybe late, but still could be useful for somebody else :) There are two good options how to insert a table into QTextEdit. 也许迟了,但对其他人仍然有用:)有两个不错的选择如何将表插入QTextEdit。
The first one, as mentioned above, is with the means of cursor. 如上所述,第一个是使用游标的方式。 Example: 例:
headers = ["Number", "Name", "Surname"]
rows = [["1", "Maik", "Mustermann"],
["2", "Tom", "Jerry"],
["3", "Jonny", "Brown"]]
cursor = results_text.textCursor()
cursor.insertTable(len(rows) + 1, len(headers))
for header in headers:
cursor.insertText(header)
cursor.movePosition(QTextCursor.NextCell)
for row in rows:
for value in row:
cursor.insertText(str(value))
cursor.movePosition(QTextCursor.NextCell)
The result then looks like following: 结果如下:
There is also another way to do this, and get more beautiful result. 还有另一种方法可以做到,并获得更漂亮的效果。 Use jinja2 package, as in the example: 使用jinja2软件包,如示例所示:
headers = ["Number", "Name", "Surname"]
rows = [["1", "Maik", "Mustermann"],
["2", "Tom", "Jerry"],
["3", "Jonny", "Brown"]]
from jinja2 import Template
table = """
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: center;
padding: 8px;
}
</style>
<table border="1" width="100%">
<tr>{% for header in headers %}<th>{{header}}</th>{% endfor %}</tr>
{% for row in rows %}<tr>
{% for element in row %}<td>
{{element}}
</td>{% endfor %}
</tr>{% endfor %}
</table>
"""
results_text.setText(Template(table).render(headers=headers, rows=rows))
You get then the styled table, as in the next picture: 您将获得样式表,如下图所示:
You need to move the position of the QTextCursor. 您需要移动QTextCursor的位置。 Take a look at QTextCursor.movePosition and the operations in QTextCursor.MoveOperation . 看看QTextCursor.movePosition和操作QTextCursor.MoveOperation 。
This should do the job for you: 这应该为您完成工作:
self.cursor.movePosition(QTextCursor.NextCell)
self.cursor.insertText("second cell")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.