How can I add or import a picture to a QWidget
? I have found a clue.
I can add a Label
and add a Picture
in that label. I need the arguments
for the QPicture()
. The probable I can use is, QLabel.setPicture(self.QPicture)
.
To load an image from a file, you can use the QPixmap. load() method. This will return a True or False value depending on whether the image was successfully loaded. Once you have loaded an image into a QPixmap, you can then display it by creating a QLabel and setting the pixmap property of the label to the QPixmap.
From the property editor dropdown select "Choose File…" and select an image file to insert. As you can see, the image is inserted, but the image is kept at its original size, cropped to the boundaries of the QLabel box. You need to resize the QLabel to be able to see the entire image.
You drag and drop your Label on your window, select the Label, you'll see on the right side of your screen the 'Property Editor' frame and the 'QLabel' menu, you click on pixmap => Choose File..., select a file and that's it. Make sure you have resized it before, you won't be able to do so in QtDesigner.
Try putting image:url(:/2. png) to see if it isn't an image format problem (for instance a JPEG file with a PNG extension that would require the jpeg plugin dll when run standalone outside of QtCreator).
Here is some code that does what you and @erelender described:
import os,sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()
window.setGeometry(0, 0, 400, 200)
pic = QtGui.QLabel(window)
pic.setGeometry(10, 10, 400, 100)
#use full ABSOLUTE path to the image, not relative
pic.setPixmap(QtGui.QPixmap(os.getcwd() + "/logo.png"))
window.show()
sys.exit(app.exec_())
A generic QWidget
does not have setPixmap()
. If this approach does not work for you, you can look at making your own custom widget that derives from QWidget
and override the paintEvent
method to display the image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With