This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Annotated URL#

Reads formatted NFC Data Exchange Format (NDEF) messages.

The Annotated URL example uses Qt NFC to display the contents of specifically formatted NFC Data Exchange Format (NDEF) messages read from an NFC Tag. The NDEF message should contain a URI record, an optional image/* MIME record, and one or more localized Text records.

This is the initial state of the example:


If a tag is touched, its NDEF content will be shown. Here is the UI for a tag that contains a text record and URI record:


When the screen is tapped, the URL will be opened in the browser.

AnnotatedUrl Class Definition#

The AnnotatedUrl class wraps QNearFieldManager , the class providing the NFC Tag detection functionality. NDEF messages are read by QNearFieldManager and forwarded to a handler contained in the AnnotatedUrl class. After parsing the NDEF message the class emits the annotatedUrl() signal. The UI reacts to the signal displaying the contents of the NDEF message.

class AnnotatedUrl(QObject):

# public
    AnnotatedUrl = explicit(QObject parent = 0)
    def startDetection():
# signals
    def annotatedUrl(url, title, pixmap):
    def nfcStateChanged(enabled):
    def tagError(error):
# public slots
    def targetDetected(target):
    def targetLost(target):
    def handleMessage(message, target):
    def handlePolledNdefMessage(message):
    def handleAdapterStateChange(state):
# private
    manager = QNearFieldManager()
    messageFilter = QNdefFilter()


The startDetection() method is used to defer the actual tag detection until all the connections between the UI and NFC-related logic are established. This is important when the application is automatically started once an NFC tag is touched. Such usecase is currently supported on Android.

if __name__ == "__main__":

    a = QApplication(argc, argv)
    mainWindow = MainWindow()
    annotatedUrl = AnnotatedUrl()
    return a.exec()

Message Filtering#

As it is mentioned above, the application supports the NDEF messages of a specific format. A correct message should contain the following fields:

  • At least one NDEF Text record, which will be used as a header.

  • Exactly one NDEF URI record.

  • An optional MIME record with an icon.

The order of the records is not strictly specified.

An instance of QNdefFilter is used to validate the NDEF message. The filter is populated as follows:

messageFilter.appendRecord<QNdefNfcTextRecord>(1, 100)
messageFilter.appendRecord<QNdefNfcUriRecord>(1, 1)
messageFilter.appendRecord(QNdefRecord.Mime, "", 0, 1)

If the incoming message does not match the filter, an error message is shown:



The NDEF Editor example application can be used to create the tags with correct or incorrect message structure.

AnnotatedUrl Handler Implementation#

NFC messages read by the QNearFieldManager are forwarded to AnnotatedUrl::handleMessage.

def handleMessage(self, message, target):

At first the messages are validated using the match() method:

if not messageFilter.match(message):
    tagError.emit("Invalid message format")

If the messages have the correct format, the parsing continues.

Because NFC messages are composed of several NDEF records, looping through all of the records allows the extraction of the 3 parameters to be displayed in the UI: the Uri, the Title and the Pixmap:

for record in message:
    if record.isRecordType<QNdefNfcTextRecord>():
        textRecord = QNdefNfcTextRecord(record)
        title = textRecord.text()
        locale = QLocale(textRecord.locale())
elif record.isRecordType<QNdefNfcUriRecord>():
   uriRecord = QNdefNfcUriRecord(record)
   url = uriRecord.uri()
elif (record.typeNameFormat() == QNdefRecord.Mime and
          record.type().startsWith("image/")) {
   pixmap = QPixmap.fromImage(QImage.fromData(record.payload()))

Finally after having extracted the parameters of the NFC message the corresponding signal is emitted so that the UI can handle it.

annotatedUrl.emit(url, title, pixmap)

Adapter State Handling#

On Android the adapter state changes can be detected by connecting to the adapterStateChanged() signal. This allows stopping the detection when the NFC adapter is disabled, and restarting it when the adapter is enabled again. This approach is implemented in the AnnotatedUrl::handleAdapterStateChange slot.

def handleAdapterStateChange(self, state):

    if state == QNearFieldManager.AdapterState.Online:
     elif state == QNearFieldManager.AdapterState.Offline:

Automatic Application Startup#

Android supports automatic application startup when the NDEF tag is touched. See Qt NFC on Android for the required changes to the Android manifest file.

Introduction of a custom AndroidManifest.xml requires special steps on the build system side.

Building with qmake#

When using qmake, the following needs to be added to the .pro file:

Building with CMake#

When using CMake, the following needs to be added to the CMakeLists.txt:

Running the Example#

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.

See also


Example project @ code.qt.io