简体   繁体   中英

Insert table into QTextEdit with PyQt4

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 ")

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: 在此处输入图片说明

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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