KDE’s KContacts framework provides API for locale-aware address formatting and address format metadata since quite some time, with an upcoming change this will all also be available for QML code directly.

Country-specific address formatting

Addresses are generally formatted differently depending on the country they are in. Such differences can be whether the state or region is relevant/included, how different parts are ordered or how different parts are joined in the local language/script.

If we have address information in a somewhat structured form, ie. broken up into individual parts (street, postal code, city, country, etc), displaying that correctly requires knowledge of those formatting rules. As this is not an uncommon problem, the KContacts framework provides C++ API for this. Using that from QML without custom glue code is now also becoming possible.

pragma ValueTypeBehavior: Addressable

import org.kde.contacts
import QtQuick.Controls

Label {
    text: {
        const addr = {
            country: "DE",
            region: "BE",
            locality: "Berlin",
            postalCode: "10969",
            street: "Prinzenstraße 85 F"
        } as address;
        return addr.formatted(KContacts.AddressFormatStyle.MultiLineInternational, "KDE e.V.");
    }
}

Different formatting styles are supported (single- or multi-line, international or domestic, for display or for postal mail labels).

Address format metadata

Additionally, the metadata necessary for formatting addresses can also be queried. This is useful for example for:

  • Showing only the input fields in an address edit form actually relevant for a specific country.
  • Input validation of postal codes, as shown in the code example below.
  • Ordering input fields in the canonical order in a given country.
import org.kde.contacts
import org.kde.kirigami
import QtQuick.Controls
import QtQuick.Layouts

RowLayout {
    TextField {
        id: postalCodeEdit
        text: "SW1P 3EU"
        property string format: AddressFormatRepository.formatForCountry("GB", KContacts.AddressFormatScriptPreference.Local).postalCodeRegularExpression
        property bool isValid: text.match("^" + format + "$")
    }
    Icon {
        source: postalCodeEdit.isValid ? "dialog-ok" : "dialog-warning"
    }
}

More elaborate examples can be found e.g. in Itinerary’s address/location editor.

What’s still missing

Review and approval of this MR.