Issue
This code assigns a raster pixmap to a label. Instead of generating one I could simply read a local file:
img = QtGui.QImage('/Users/user/Desktop/photo.jpg')
I wonder if there is a way to specify the URL link instead of file path? Then QLabel
would get its pixmap straight from a web?
from PyQt4 import QtCore, QtGui
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
if not QtGui.QApplication.instance():
app=QtGui.QApplication([])
window = QtGui.QWidget()
window.setLayout(QtGui.QVBoxLayout())
img = QtGui.QImage(32, 32, QtGui.QImage.Format_RGB32)
img.fill(QtCore.Qt.red)
pixmap = QtGui.QPixmap(img)
lbl = QtGui.QLabel()
lbl.setPixmap(pixmap)
icon = QtGui.QIcon(pixmap)
window.layout().addWidget(lbl)
window.show()
sys.exit(app.exec_())
Solution
To my knowledge, there is no direct way of getting a QImage or QPixMap to load data straight from a URL. But you can bypass that by first extracting the data from the URL, and then loading it to a QPixMap.
Get data from the URL:
import urllib2
url_data = urllib2.urlopen(path).read()
Now load it to your QPixMap:
pixmap = QPixmap()
pixmap.loadFromData(url_data)
lbl.setPixmap(pixmap)
It is worth saying you should try and catch exceptions like urllib2.URLError
or InvalidURL
, handle cases where the URL is secured (https) etc.
Answered By - Matanoga
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.