Anion
Anion

Reputation: 65

How do vertically center text next to an image in QTextBrowser?

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_())

Upvotes: 2

Views: 1266

Answers (1)

bakatrouble
bakatrouble

Reputation: 1844

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_())

Upvotes: 1

Related Questions