Reputation: 337
How can I insert a tabel inside a QTextEdit to be printed on A4 paper. 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 ")
Upvotes: 3
Views: 3890
Reputation: 95
Maybe late, but still could be useful for somebody else :) There are two good options how to insert a table into 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:
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:
Upvotes: 3
Reputation: 4510
You need to move the position of the QTextCursor. Take a look at QTextCursor.movePosition and the operations in QTextCursor.MoveOperation.
This should do the job for you:
self.cursor.movePosition(QTextCursor.NextCell)
self.cursor.insertText("second cell")
Upvotes: 1