2011-11-27 89 views
2

如何在QTextEdit中插入要在A4紙上打印的表格。我寫了這個代碼,但我不知道我可以將其插入值,只需插入第一個單元格:使用PyQt4將表格插入QTextEdit

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

回答

0

你需要移動QTextCursor的位置。看看QTextCursor.movePositionQTextCursor.MoveOperation中的操作。

這應該爲你做的工作:

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

非常感謝,如果我需要合併兩列,我可以做什麼,我嘗試使用此代碼self.table = QTextTable()self.cursor.insertTable(2,5,表),當我運行它時,沒有發生任何事情,如果我不使QTextTable它工作良好,但我需要合併單元格我可以做到這一點,而不使QTextTable? –

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