I got a QLabel with a Rich Text which contains Texts and Images.
The Label:
self.Informations = QtWidgets.QLabel(self.Home)
self.Informations.setGeometry(QtCore.QRect(470, 160, 651, 71))
self.Informations.setTextFormat(QtCore.Qt.RichText)
font = QtGui.QFont()
font.setPointSize(18)
self.Informations.setFont(font)
self.Informations.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
self.Informations.setTextInteractionFlags(
QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextSelectableByKeyboard | QtCore.Qt.TextSelectableByMouse)
self.Informations.setObjectName("Informations")
The Rich Text:
self.Informations.setText(f"<html><head/><body><p><span style=\" font-size:18pt;\">Account Level: {Account_level}<br>Current Rank: {Rank} </span><img src=\"{tier_png_url}\" width=\"29\" height=\"29\"/><span style=\" font-size:18pt;\"> {RR}rr</span></p></body></html>")
thats the html shape im using, everything works fine except the image. It is a "blank" image looking like this: Now im looking for a fix. The other things like Texts etc. are working fine
the variable {tier_png_url} is a png url, which comes from a api example from the api:
CodePudding user response:
A QLabel can only render static html. The LinksAccessibleByMouse
flag just means clicking on links will emit a linkActivated signal. The QLabel itself has no network access, so it cannot do anything with urls. But even if it could, using hard-coded third-party urls in your aspplication is probably not a good idea, since the urls could change at any time.
To render your image more reliably, you should therefore download it first and save it to disk. I suggest you put it in an "images" subfolder witihin the same folder as your main script. This will make it easier to create the correct image path at runtime.
Below is a demo script based on your example code that shows how to do this:
from pathlib import Path
from PyQt5 import QtCore, QtGui, QtWidgets
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.Informations = QtWidgets.QLabel(self)
self.Informations.setAlignment(
QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
self.Informations.setTextInteractionFlags(
QtCore.Qt.TextSelectableByKeyboard |
QtCore.Qt.TextSelectableByMouse)
self.Informations.setObjectName("Informations")
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.Informations)
Account_level = 117
Rank = 'Gold 3'
RR = 67
tier_icon = Path(__file__).parent.joinpath('images/tier.png')
self.Informations.setText(f"""
<html><head/><body><p>
<span style="font-size: 18pt;">
Account Level: {Account_level}<br>
Current Rank: {Rank}
</span>
<img src="{tier_icon}" width="29" height="29"/>
<span style="font-size: 18pt;">{RR}rr</span>
</p></body></html>
""")
if __name__ == '__main__':
app = QtWidgets.QApplication(['Test'])
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
app.exec_()