如何解决QML Timer切换图片时出现的qrc:/undefined加载错误?
问题原因
你遇到的QML Image: Cannot open: qrc:/undefined错误,是因为使用Qt.binding将source和counter做了绑定,当counter递增到3(超出fileNames数组最大索引2)时,绑定会自动触发source更新,此时fileNames[3]不存在返回undefined,导致图片路径无效。同时你给Image的source默认绑定了counter,两种绑定逻辑叠加也会引发冲突。
解决方案
以下提供两种可行修改方式,推荐第一种利用QML属性绑定的简洁方案:
方案一:利用属性自动绑定(推荐)
让Image的source自动跟随counter变化,只需在Timer中更新counter即可:
Window { width: 640 height: 480 visible: true title: qsTr("Hello World") property var fileNames: [ "battery-charging-empty-icon.svg", "battery-charging-full-icon.svg", "battery-charging-half-icon.svg" ] property int counter: 0 property bool execute: qmlSample.chargingStatus // 从Qt-C++设置 Timer { id: timerId interval: 1000 repeat: true running: true onTriggered: { if(execute) { counter += 1 // 用数组长度判断,避免写死索引值,适配数组长度变化 if(counter >= fileNames.length) { counter = 0 } } } } Image { id: imageId property size size: Qt.size(100, 100) anchors.centerIn: parent source: "qrc:/" + fileNames[counter] } }
方案二:手动控制source赋值
移除Image的source绑定逻辑,直接在Timer中手动赋值,同时避免使用Qt.binding:
Window { width: 640 height: 480 visible: true title: qsTr("Hello World") property var fileNames: [ "battery-charging-empty-icon.svg", "battery-charging-full-icon.svg", "battery-charging-half-icon.svg" ] property int counter: 0 property bool execute: qmlSample.chargingStatus // 从Qt-C++设置 Timer { id: timerId interval: 1000 repeat: true running: true onTriggered: { if(execute) { // 直接赋值当前counter对应的图片 imageId.source = "qrc:/" + fileNames[counter] counter += 1 // 超过数组长度时重置 if(counter >= fileNames.length) { counter = 0 } } } } Image { id: imageId property size size: Qt.size(100, 100) anchors.centerIn: parent // 初始显示第一张图 source: "qrc:/" + fileNames[0] } }
内容的提问来源于stack exchange,提问作者praveen
相关产品推荐
相关产品推荐

