PyQt4 QTextEdit中HTML表格内文本垂直显示问题求助
在PyQt4的QTextEdit中实现垂直文本的解决方案
我完全懂你遇到的困扰——Qt的QTextEdit虽然支持HTML,但它的富文本引擎对CSS的支持和主流浏览器差得挺多,你用的writing-mode这类属性刚好不在它的支持范围内,所以浏览器能正常显示,TextEdit却没反应。
下面给你几个可行的替代方案,都是在PyQt4环境下能正常工作的:
方法1:在HTML中嵌入SVG实现垂直文本
这是改动最小的方案,因为你原本就是用HTML来构建报表的。Qt的QTextEdit支持渲染SVG,所以可以把垂直文本放在SVG元素里,嵌入到HTML的表格单元格中:
<html> <head> <title>QTextEdit Demonstration</title> </head> <body> <table align="center" border="1" cellpadding="4" cellspacing="0" width="99%"> <tr> <td> <!-- 用SVG绘制垂直文本 --> <svg width="60" height="60"> <text x="30" y="30" text-anchor="middle" dominant-baseline="middle" transform="rotate(90 30 30)" font-size="14px" >vertical</text> </svg> </td> <td><p><span>horizontal</span></p></td> <td><p><span>0</span></p></td></tr> </table> </body> </html>
你可以调整rotate的角度(比如改成270就是反向垂直)、字体大小、SVG的宽高来适配你的报表需求。
方法2:用PyQt4代码直接操作QTextDocument
如果不想依赖SVG,也可以通过纯Qt代码的方式来构建表格并设置垂直文本,这种方式更灵活,可控性更强:
from PyQt4.QtGui import (QApplication, QTextEdit, QTextDocument, QTextCursor, QTextTableFormat, QTextCharFormat, QTextBlockFormat) from PyQt4.QtCore import Qt import sys app = QApplication(sys.argv) text_edit = QTextEdit() doc = text_edit.document() cursor = QTextCursor(doc) # 配置表格格式 table_format = QTextTableFormat() table_format.setAlignment(Qt.AlignCenter) table_format.setBorder(1) table_format.setCellPadding(4) table_format.setCellSpacing(0) table_format.setWidth(QTextLength(QTextLength.PercentageLength, 99)) # 插入1行3列的表格 table = cursor.insertTable(1, 3, table_format) # 处理第一个单元格的垂直文本 cell_cursor = table.cellAt(0, 0).firstCursorPosition() # 设置单元格内文本块的对齐方式 block_format = QTextBlockFormat() block_format.setAlignment(Qt.AlignCenter) cell_cursor.setBlockFormat(block_format) # 创建旋转的字符格式(实现垂直效果) char_format = QTextCharFormat() # 这里通过旋转字符来模拟垂直显示,角度可调整 char_format.setRotation(90) cell_cursor.setCharFormat(char_format) # 插入文本 cell_cursor.insertText("vertical") # 其他单元格正常插入文本 cell_cursor = table.cellAt(0, 1).firstCursorPosition() cell_cursor.insertText("horizontal") cell_cursor = table.cellAt(0, 2).firstCursorPosition() cell_cursor.insertText("0") text_edit.show() sys.exit(app.exec_())
为什么原来的CSS无效?
Qt的QTextDocument(QTextEdit的核心)只支持有限的CSS子集,像writing-mode、filter这类现代CSS属性并没有被实现,所以浏览器能解析的样式,在Qt富文本里就失效了。
内容的提问来源于stack exchange,提问作者neurocker
相关产品推荐
相关产品推荐

