使用PyQt4将表插入QTextEdit

时间:2011-11-27 17:24:32

标签: python qt4 pyqt4

如何在QTextEdit中插入要在A4纸上打印的表格。我写了这段代码,但我不知道如何将其插入到值中,只需插入第一个单元格:

self.text = QtGui.QTextEdit()
self.cursor = QtGui.QTextCursor()
self.cursor = self.text.textCursor()
self.cursor.insertTable(2, 5)
self.cursor.insertText("first cell ")

2 个答案:

答案 0 :(得分:0)

您需要移动QTextCursor的位置。请查看QTextCursor.movePosition以及QTextCursor.MoveOperation中的操作。

这应该适合你:

self.cursor.movePosition(QTextCursor.NextCell)
self.cursor.insertText("second cell")

答案 1 :(得分:0)

也许迟到了,但对其他人来说仍然有用:) 如何将表插入QTextEdit有两个很好的选择。

如上所述,第一个是光标。 例如:

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)

结果如下: enter image description here

还有另一种方法可以做到这一点,并获得更美丽的结果。使用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))

然后你会得到样式表,如下图所示: enter image description here

相关问题