SdahlSean
SdahlSean

Reputation: 583

Putting images and text in QLabel

I have a list of paragraphs like this:

list1 = [
  "something",
  "more",
  ...
  "{ //image// }"
  "something"
  ...
  "{ //image// }"
  ...
]

The "{ //image// }" text occurs a known amount in the list. I have another list with paths to images which has the same length as the amount of occurrences of the text:

list2 = [
  "path1",
  "path2"
]

Now I am working with pyqt and I want to show all the elements of the first list in a QLabel. I am doing this like that:

paragraphs = ""
for element in list1:
    elements += element + "<br>"
my_QLabel.setText(elements)

Now I want to replace every occurrence of the String { //image// } in the QLabel with an image from the second list. How can I do that while still keeping the other text?

Upvotes: 2

Views: 396

Answers (1)

eyllanesc
eyllanesc

Reputation: 244301

Assuming that the amount of {// image //} in the first list matches the length of the second list. In this case you can implement a logic to replace:

from PyQt5 import QtCore, QtGui, QtWidgets


def build_text(texts, images, word):
    image_format = """<img src="{}" width="100" height="100">"""
    images_iter = iter(images)
    text = "<br>".join(
        [
            image_format.format(next(images_iter)) if e == word else e
            for e in texts
        ]
    )
    return text


if __name__ == "__main__":
    import sys

    list1 = [
        "something",
        "more",
        "{ //image// }",
        "something",
        "{ //image// }",
        "{ //image// }",
        "more",
        "{ //image// }",
    ]

    list2 = [
        "/path/of/image1.png",
        "/path/of/image2.png",
        "/path/of/image3.png",
        "/path/of/image4.png",
    ]
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QLabel()
    text = build_text(list1, list2, "{ //image// }")
    w.setText(text)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

Upvotes: 1

Related Questions