将PyQt中的QTreeWidget转换为ReportLab中的表格

1 投票
1 回答
606 浏览
提问于 2025-04-17 10:03

在ReportLab中,表格看起来有点复杂,所以我想找个简单的方法,把两段文字分别放在页面的左边和右边(如果可以的话,最好通过Paragraph类来实现)。我在网上找了很久,似乎没有找到相关的解释。所以,如果这可能的话,应该怎么做呢?

最后,我想实现的目标是把PyQT中的QTreeWidget的数据转换成一个外观相似的PDF。

提前谢谢大家!

1 个回答

0

看起来,完成这个任务最好的方法是使用表格。虽然这个过程有点复杂,但学习表格数据的嵌套列表结构是解决问题的关键。转换QTreeWidget数据的关键在于下面的代码,你需要在处理表格数据时动态地添加数据和单元格样式。

假设QTreeWidget的结构只是包含两列文本(0和1)的项目,下面的代码就可以用了。

from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

pdf = SimpleDocTemplate("TreeWidgetPDF.pdf", pagesize = letter)
data = []
tStyle = []

for x in QTreeWidgetData.findItems("*", Qt.MatchWildcard, 0):
    project = str(x.text(0))
    data.append([project, x.text(1)])
    tStyle.append(('BACKGROUND', (0, cell), (1, cell), 'YELLOW'))
    tStyle.append(('FONTSIZE', (0, cell), (1, cell), 12))
    cell+=1

    for y in range(x.childCount()):
        data.append([str(x.child(y).text(0)), str(x.child(y).text(1))])
        tStyle.append(('ALIGN', (1, cell), (1, cell), 'RIGHT'))
        tStyle.append(('LEFTPADDING', (0, cell), (0, cell), 15))
        cell+=1

        for z in range(x.child(y).childCount()):
            data.append([x.child(y).child(z).text(0), x.child(y).child(z).text(1)])
            tStyle.append(('ALIGN', (1, cell), (1, cell), 'RIGHT'))
            tStyle.append(('LEFTPADDING', (0, cell), (0, cell), 30))
            cell+=1

        # And so on and so forth. You could probably iterate through this in a 
        # While loop so you don't have to manually nest your for statements.

parts = []
styledTable = Table(data, [6 * inch, 1 * inch, 0])
styledTable.setStyle(TableStyle(tStyle))
parts.append(table_with_style)
pdf.build(parts)

撰写回答