#python #python-3.x #pyside #pyside6
Вопрос:
Я пытаюсь отобразить изображение с URL-адреса в pyside6, но ничего не получается.
def getIcon(data):
iconID = data['weather'][0]['icon']
icon = QPixmap("http://openweathermap.org/img/w/" iconID ".png");
return icon
И
self.temperatureIcon = QtWidgets.QLabel(self).setPixmap(getIcon(self.weatherData))
это код, который у меня есть.
Ответ №1:
QPixmap не загружает изображение с URL-адреса, поэтому вы должны загрузить его, например, с помощью QNetworkAccessManager:
import sys
from functools import cached_property
from PySide6.QtCore import Signal, QObject, Qt, QUrl
from PySide6.QtGui import QImage, QPixmap
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
from PySide6.QtWidgets import (
QApplication,
QGridLayout,
QLabel,
QLineEdit,
QPushButton,
QWidget,
)
class ImageDownloader(QObject):
finished = Signal(QImage)
def __init__(self, parent=None):
super().__init__(parent)
self.manager.finished.connect(self.handle_finished)
@cached_property
def manager(self):
return QNetworkAccessManager()
def start_download(self, url):
self.manager.get(QNetworkRequest(url))
def handle_finished(self, reply):
if reply.error() != QNetworkReply.NoError:
print("error: ", reply.errorString())
return
image = QImage()
image.loadFromData(reply.readAll())
self.finished.emit(image)
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.lineedit = QLineEdit()
self.button = QPushButton("Start")
self.label = QLabel(alignment=Qt.AlignCenter)
lay = QGridLayout(self)
lay.addWidget(self.lineedit, 0, 0)
lay.addWidget(self.button, 0, 1)
lay.addWidget(self.label, 1, 0, 1, 2)
self.downloader = ImageDownloader()
self.downloader.finished.connect(self.handle_finished)
self.button.clicked.connect(self.handle_clicked)
self.lineedit.setText("http://openweathermap.org/img/wn/01d@2x.png")
self.resize(640, 480)
def handle_finished(self, image):
pixmap = QPixmap.fromImage(image)
self.label.setPixmap(pixmap)
def handle_clicked(self):
url = QUrl.fromUserInput(self.lineedit.text())
self.downloader.start_download(url)
def main():
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
Ответ №2:
Вот еще одно простое решениепример:
import sys
import requests
from PySide6.QtGui import QPixmap, QScreen
from PySide6.QtWidgets import QApplication, QWidget, QLabel
URL = 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_(test_image).png'
class App(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('getAndSetImageFromURL()')
self.label = QLabel(self)
self.pixmap = QPixmap()
self.getAndSetImageFromURL(URL)
self.resize(self.pixmap.width(),self.pixmap.height())
screenSize = QScreen.availableGeometry(QApplication.primaryScreen())
frmX = (screenSize.width () - self.width ())/2
frmY = (screenSize.height() - self.height())/2
self.move(frmX, frmY)
self.show()
def getAndSetImageFromURL(self,imageURL):
request = requests.get(imageURL)
self.pixmap.loadFromData(request.content)
self.label.setPixmap(self.pixmap)
#QApplication.processEvents() # uncoment if executed on loop
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = App()
sys.exit(app.exec())