Android QML中QtSensors5.0的ProximitySensor使用异常求助
Hey there! Let's break down the issues you're facing with the ProximitySensor in QtSensors 5.0 for QML—since you confirmed the hardware works, the problem is almost certainly in how you're interacting with the QML API.
First, Let's Fix the Core Setup
It sounds like you might be missing some key parts of the QML sensor structure. Here's a working minimal example that should address most of your issues:
import QtQuick 2.0 import QtSensors 5.0 Item { width: 300 height: 300 // Define the sensor with an ID so you can reference it ProximitySensor { id: proximitySensor // Set active to true to start the sensor automatically active: true // Listen for new readings (this is where valid data will be available) onReadingChanged: { console.log("Object near?", reading.near); // You can also access other reading properties like timestamp here } } // Display the current status Text { anchors.centerIn: parent text: proximitySensor.reading ? (proximitySensor.reading.near ? "Object is close!" : "No object nearby") : "Sensor starting up..." } // Example button to control the sensor (uses stop()/start(), not close()) Button { text: proximitySensor.active ? "Turn Off Sensor" : "Turn On Sensor" anchors.bottom: parent.bottom anchors.horizontalCenter: parent.horizontalCenter onClicked: { if (proximitySensor.active) { proximitySensor.stop(); } else { proximitySensor.start(); } } } }
Let's Address Your Specific Issues
Reading only shows deleteLater, objectName, timestamp
This happens when you try to access thereadingproperty before the sensor has initialized or started producing data. Always accessreadingeither in theonReadingChangedsignal handler (triggered when new data arrives) or check ifreadingexists first (like in the Text element above).ProximityReading.near returns undefined
Again, this is tied to timing—you're trying to readnearbefore the sensor has valid data. Wait for theonReadingChangedsignal, or ensure the sensor is active (active: trueorstart()called) before accessing the property.proximitySensor.close() says "undefined"
Two issues here:- You probably didn't set an
id: proximitySensoron your ProximitySensor component, so the code can't find the object. - QtSensors uses
stop()to disable the sensor, notclose()—close()isn't a valid method for this class. UseproximitySensor.stop()instead.
- You probably didn't set an
Quick Checklist to Double-Check
- Make sure your
.proproject file includesQT += sensorsto link the sensors module. - Confirm you have the correct import:
import QtSensors 5.0(not a newer version, since you're using 5.0). - Test on your target device (emulators often don't support proximity sensors, but you said your phone works, so this is covered).
内容的提问来源于stack exchange,提问作者Fagner Fonseca

