V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
NxnXgpuPSfsIT
V2EX  ›  Python

qt 富文本排版求助

  •  
  •   NxnXgpuPSfsIT ·
    littlecodersh · 2016-11-07 18:02:33 +08:00 · 3000 次点击
    这是一个创建于 2735 天前的主题,其中的信息可能已经有所发展或是发生改变。

    qt 富文本排版求助

    尝试了很久都没能解决,特别做了整理,万望各位不吝赐教!

    问题

    1. 如何使用 qt 富文本在同一行中左右分别放置内容
    2. 如何正确的组合 QTextFrame 等内容

    如何使用 qt 富文本在同一行中左右分别放置内容

    简而言之,需要在 QLabel 的一行里左对齐放置一些文字,右对齐放置一些文字。

    关于限定 QLabel :

    • 由于需要跨 QLabel 选择文字,所以无法使用 layout
    • 由于之后的内容需要自动折行,所以 paintEvent 也并不容易
    • 不过 QTextEdit 是可行的

    目前的尝试:

    • 尝试过使用 qt 支持的富文本,没有找到可用的属性(至多使用 div 的 float 属性,在两行中左右放置)
    • 尝试过使用 qt 的 QTextDocument 等内容在 QTextEdit 中拼接,没有找到可用的方法

    如何正确的组合 QTextFrame 等内容

    QTextFrame 等内容在拼接过程中会产生多余的行。

    以以下简化过的需求为例:

    • 类聊天框,两条信息背景颜色不同
    • 消息全文左右空出 10px (这是为什么要在 QTextFrame 里面套 QTextBlock 的原因,只是写着不需要实现)

    实现代码基本如下:

    import sys
    from PyQt4.QtGui import *
    
    msgList = ['Hi', 'Hello', 'How are you', 'Fine thank you and you im fine too']
    
    app = QApplication(sys.argv)
    
    ted = QTextEdit()
    cursor = ted.textCursor()
    for i, msg in enumerate(msgList):
        frameFormat = QTextFrameFormat()
        frameFormat.setBackground(QColor(227, 239, 255)
            if i % 2 else QColor(129, 134, 144))
        blockFormat = QTextBlockFormat()
        blockFormat.setLeftMargin(10)
    
        cursor.movePosition(QTextCursor.End)
        cursor.insertFrame(frameFormat)
        cursor.insertBlock(blockFormat)
        cursor.insertText(msg)
    
    mainWindow = QWidget()
    layout = QVBoxLayout()
    layout.addWidget(ted)
    mainWindow.setLayout(layout)
    mainWindow.show()
    sys.exit(app.exec_())
    

    产生问题:

    QTextFrame 和 QTextBlock 都会产生一行计划之外的空行,分别对应图中 1 和 2 。

    unexpected-lines

    由于 V2EX 的回复代码的问题,可能要麻烦使用 gist 等方式分享代码。

    使用 c++或者 python 都可以。

    尝试了很久都没能解决,万望各位不吝赐教!

    2 条回复    2016-11-07 19:11:30 +08:00
    fqzz
        1
    fqzz  
       2016-11-07 18:58:09 +08:00
    转成 html 显示
    NxnXgpuPSfsIT
        2
    NxnXgpuPSfsIT  
    OP
       2016-11-07 19:11:30 +08:00
    @fqzz 感谢您的回复,可以麻烦简单的贴一下代码吗?
    提问前我已经将可以想到的 html 实现都做了尝试,但 qt 的富文本只支持部分的 html4 ,没能找到解决方案。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2334 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 10:33 · PVG 18:33 · LAX 03:33 · JFK 06:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.