-2

I am making a podcast application where I want to display channel icons. That's where I asked myself : How do I properly display a picture in PyQt5 ? I read about this:

label = QLabel()
pixmap = QPixmap('image.png')
label.setPixmap(pixmap)

It's often done that way, but I feel a bit, well, uneasy, about it. It feels hackish to me even though there is an extra method to do it like this. Is there any docs passage where the above way is defined as the official standard one ? If not, is there a better way ? Something like

lay = QVBoxLayout()
image = SomeWidget("image.png")
lay.addWidget(image)
TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • What makes you think that it's "hackish"? – musicamante Apr 23 '21 at 21:52
  • @musicamante "What makes you think that it's hackish" - well, I create a Label _and_ a pixmap, only to add that pixmap to the label - I think that's an overkill. It would be much more natural to just have a widget you give a path to eat, and then you can add the widget to your layout or whatever, and done. – TheEagle Apr 23 '21 at 21:53
  • 1
    That's your point of view. While its main purpose is showing some text, QLabel is actually a complex widget, which supports images and framing (since it inherits QFrame). The ability to show images is just one of its features, but *not* its main one, so it makes sense that you have to add some more commands in order to show it; also, since QLabel already has the ability to show images, it doesn't make sense to have a separate class for that. – musicamante Apr 23 '21 at 21:59
  • @musicamante okay, if you add that to your answer, I'll accept it – TheEagle Apr 23 '21 at 21:59

1 Answers1

0

All Qt subclasses of QObject (which includes all subclasses of QWidget, since it inherits from QObject) allow setting their Qt properties in the constructor as keyword arguments.

Since pixmap is a property of QLabel, you can create one directly with an image set with the following line:

image = QLabel(pixmap=QPixmap('image.png'))

If you are so bothered about that, then just create a convenience function or class:

def ImageWidget(path):
    return QLabel(pixmap=QPixmap(path))

# or, alternatively

class ImageWidget(QLabel):
    def __init__(self, path):
        super().__init__(pixmap=QPixmap(path))
musicamante
  • 41,230
  • 6
  • 33
  • 58