2

How can I vertically center text that's next to an image correctly in QTextBrowser? I tried using this answer for HTML, but it doesn't correctly center it. This kind of works for larger images though. I also tried using self.textBrowser.setStyleSheet("vertical-align: middle;") but to no avail.

Larger icon:

enter image description here

Small icon:

Small icon

My code:

import sys
from PyQt5.QtWidgets import *

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.resize(300, 170)

        self.textBrowser = QTextBrowser(self)
        self.textBrowser.document().setHtml("""
<div>
    <img src="icons/info1.png" style="vertical-align: middle;"/>
    <span style="vertical-align: middle;">Here is some text.</span>
</div>""")

        self.layout = QGridLayout()
        self.layout.addWidget(self.textBrowser)
        self.setLayout(self.layout)

app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
Community
  • 1
  • 1
Anion
  • 65
  • 1
  • 7
  • 1
    http://doc.qt.io/qt-5/richtext-html-subset.html Here's description of HTML subset supported in Qt, looks like you may need to create a table. – bakatrouble Jul 14 '17 at 08:18
  • 1
    Also consider using standard Qt layouts if there's no content that could be displayed only in `QTextBrowser` – bakatrouble Jul 14 '17 at 08:26

1 Answers1

1

You could use html tables, vertical alignment works fine then

import sys

from PyQt5.QtWidgets import *


class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.resize(300, 170)

        self.textBrowser = QTextBrowser(self)
        self.textBrowser.document().setHtml("""
<table width="100%">
    <tr>
        <td><img height="500" src="icons/info1.png"/></td>
        <td style="vertical-align: middle;">Here is some text.</td>
    </tr>
</table>
""")

        self.layout = QGridLayout()
        self.layout.addWidget(self.textBrowser)
        self.setLayout(self.layout)

app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
bakatrouble
  • 1,746
  • 13
  • 19