如何将XMLHttpRequest获取的数据渲染到QML GridView并解决图片加载问题
问题根因
- TMDB接口返回的
backdrop_path仅为图片相对路径,不是可直接访问的完整HTTP地址,直接赋值给Image组件的source属性会导致找不到资源报错。 - GridView未配置正确的单元格尺寸参数,无法实现每行5部电影的布局效果。
修复方案
1. 补全图片访问路径
TMDB的静态资源基础地址为https://image.tmdb.org/t/p/,需要根据所需尺寸拼接完整路径,示例:拼接w500尺寸的海报地址为 https://image.tmdb.org/t/p/w500 + 接口返回的backdrop_path。
2. 调整GridView布局参数
给GridView设置cellWidth为窗口宽度的1/5,匹配每行5部的需求,同时设置对应的cellHeight保证布局整齐。
3. 可选优化:启动时自动加载数据
原代码仅在按上键时触发接口请求,可在组件初始化完成后自动调用请求方法。
修复后代码
import QtQuick 2.15 import QtQuick.Window 2.15 Window { width: 1920 height: 1080 visible: true title: qsTr("电影列表") // TMDB图片基础配置,可按需调整尺寸 readonly property string tmdbImageBase: "https://image.tmdb.org/t/p/w500" Component.onCompleted: { mojgrid.focus = true // 启动自动加载数据,不需要可删除 request() } function dobioResponseNapraviModel(response) { console.log("dobioResponseNapraviModel", typeof response) mojgrid.model=response } function request(){ console.log("BOK") const xhr=new XMLHttpRequest() const method="GET"; const url="https://api.themoviedb.org/4/list/1"; xhr.open(method, url, true); xhr.setRequestHeader( "Authorization", 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5YjBkOGVlMGQzODdiNjdhYTY0ZjAzZDllODM5MmViMyIsInN1YiI6IjU2MjlmNDBlYzNhMzY4MWI1ZTAwMTkxMyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.UxgW0dUhS62m41KjqEf35RWfpw4ghCbnSmSq4bsB32o'); xhr.onreadystatechange=function(){ if(xhr.readyState===XMLHttpRequest.DONE){ var status=xhr.status; if(status===0 || (status>=200 && status<400)){ dobioResponseNapraviModel(JSON.parse(xhr.responseText).results) }else{ console.log("There has been an error with the request", status, JSON.stringify(xhr.responseText)) } } } xhr.send(); } GridView { id:mojgrid anchors.fill: parent // 每行5个,单元格宽度为窗口宽度的1/5 cellWidth: width / 5 cellHeight: 400 Keys.onUpPressed: { request() } delegate: Rectangle{ width: mojgrid.cellWidth height: mojgrid.cellHeight color:'gray' Image{ anchors.fill:parent fillMode: Image.PreserveAspectFit // 拼接完整图片地址 source: tmdbImageBase + modelData.backdrop_path } Text{ text:modelData.original_title anchors.bottom: parent.bottom color: "white" background: Rectangle { color: "black"; opacity: 0.7; anchors.fill: parent } } } } }
内容的提问来源于stack exchange,提问作者irena
相关产品推荐
相关产品推荐

