Jump to content

Qt for HarmonyOS/user development guide/application share guild

From Qt Wiki

English 中文

Qt for HarmonyOS Share Kit Integration Guide

This document is based on the following examples and is intended to help developers quickly integrate Share Kit sharing capabilities into Qt for HarmonyOS applications:

  • Sender Demo: qtohosextras/examples/qtohosextras/abilitycontext/sharedata (core file: main.cpp)
  • Receiver Demo: qtohosextras/examples/qtohosextras/abilitycontext/sharedatareceiver (core file: main.cpp)

1. Goals and Scope

  1. Explain how to build share content in Qt Widgets / Qt Quick applications and open the system share panel via QtOhosExtras::ShareKit.
  2. Describe how the receiver parses QOhosSharedRecord injected by Share Kit during Ability startup or runtime.
  3. Provide key steps for build, deployment, debugging, and common troubleshooting.

2. Development Environment and Dependencies

Component Description
Qt Modules QtWidgets, QtOhosExtras (including ShareKit, QOhosAbilityContext, QOhosAppContext, etc.)
Build Tools qmake + make, or CMake kit integrated with DevEco Studio
Runtime Environment HarmonyOS devices that support Share Kit

Note: Share Kit performs permission authorization through the system share panel by default. Manual permission declaration is usually not required, but the target device must support Share Kit.

2.1 module.json5 Configuration (Receiver *Required*)

Declare skills filters for the receiving UIAbility in the application's module.json5:

{
  "abilities": [
    {
      "name": "EntryAbility",
      "skills": [
        {
          "actions": [
            "ohos.want.action.sendData"
          ],
          "uris": [
            {
              "scheme": "file",
              "utd": "general.image",
              "maxFileSupported": 9
            }
          ]
        }
      ]
    }
  ],
  "requestPermissions": [
    { "name": "ohos.permission.INTERNET" }
  ]
}
  • The action must be set to `ohos.want.action.sendData`
  • `uris.utd` must enumerate all data types supported by the receiver (following the UTD predefined list)
  • Share Kit official limitations:
 1. Total size of share data descriptions ≤ 200 KB
 2. Total number of records ≤ 500
  • If this configuration is missing or incorrect, the application will not appear in the system share panel candidate list

3. Sender Implementation Guide

Reference: sharedata/main.cpp

3.1 Key Steps

1. Prepare Share Records

  • Text record:
 QtOhosExtras::ShareKit::createContentRecord(QMimeType, QString)
  • File record:
 createFileRecord(const QFileInfo &) (MIME type inferred automatically)
  • Thumbnail (optional):
 Load :/qt_logo.png and set it via setThumbnail()

2. Configure Record Metadata

Enhance system panel presentation using the following APIs:

  • setTitle()
  • setDescription()
  • setLabel()
  • setExtraData()

3. Configure Controller Options (Optional)

  • QtOhosExtras::ShareKit::createControllerOptions()
  • setSingleSelectionMode()
  • setDefaultPreviewMode()
  • setAnchor(x, y) (fix popup position in large-screen scenarios)

4. Invoke Share API

  • Obtain context via QOhosAbilityContext::getDefaultInstance()
  • Call: shareDataWithShareKit(records, controllerOptionsOrNull)
  • Share Kit opens the system share panel and waits for user selection

5. UI Interaction Recommendations

  • The demo uses checkboxes / SpinBox widgets to adjust controller parameters
  • Use m_recordsToShareLabel to indicate the current number of records to be shared

3.2 Controller Options Form Description

Control Purpose
Add Text/File Record Add a text or file record
Remove Records Clear all current share records
Use Controller Options Master switch for controller options
Default Preview Mode Enable or disable default preview
Single Selection Mode Restrict to a single receiver
Anchor X / Y Set share panel anchor position

3.3 Code Example

auto record = QtOhosExtras::ShareKit::createContentRecord(
    QMimeDatabase().mimeTypeForName("text/plain"),
    QStringLiteral("Record %1 Content").arg(index));

record->setTitle(QStringLiteral("Record %1 Title").arg(index));
record->setDescription(QStringLiteral("Record %1 Description").arg(index));

auto abilityContext = QtOhosExtras::QOhosAbilityContext::getDefaultInstance();
abilityContext->shareDataWithShareKit({ record }, controllerOptionsOrNull);

3.4 Multiple Record Sharing

  • Share Kit supports sharing multiple `QOhosSharedRecord` instances at once
  • It is recommended to limit the number and total size of records per share
  • Clearly indicate the shared content in the UI

4. Receiver Implementation Guide

Reference: sharedatareceiver/main.cpp

4.1 Startup Parsing

  1. Call `QOhosAppContext::getAppLaunchWantInfo()`
  2. Parse share data via `tryGetSharedRecordsFromShareKit()`
  3. Convert `QOhosSharedRecord` objects into application business data

4.2 Runtime Listening

  1. Connect to the `newWantInfoReceived` signal
  2. Repeat the parsing process in the callback to support multiple share events

4.3 UI Presentation

  • The demo uses `QTextEdit` for log output
  • Before reading files, validate accessibility:
 QFileInfo(record->filePath()).isReadable()

5. Share Data Record Field Description

Field Set by Sender Read by Receiver Notes
MIME Type createContentRecord / createFileRecord record->mimeType().name() Distinguishes text, image, etc.
Text Content createContentRecord record->content() Empty for file records
File Path createFileRecord record->filePath() Points to a system temporary copy; can be deleted after reading
Title / Description / Label setTitle / setDescription / setLabel record->title(), etc. Displayed in share panel
Thumbnail setThumbnail Not required Used only for system share panel preview
extraData setExtraData record->extraData() Custom business extension fields

6. Build and Deployment

6.1 Command Line

# Sender
cd qtohosextras/examples/qtohosextras/abilitycontext/sharedata
qmake sharedata.pro
make

# Receiver
cd qtohosextras/examples/qtohosextras/abilitycontext/sharedatareceiver
qmake sharedatareceiver.pro
make

6.2 Runtime Verification

  1. Install the receiver application
  2. Launch the sender demo
  3. Click “Share Records”
  4. Verify received data in the receiver UI

7. Common Issues and Troubleshooting

Issue Troubleshooting
Share panel does not appear Ensure QtOhosExtras is correctly packaged and the device supports Share Kit
Receiver gets no data Verify records are not empty; ensure the receiver app is selected in the share panel; print raw Want data if needed
File path not readable Check QFileInfo::isReadable() before accessing the file
Multiple shares overwrite data Use extraData or add timestamps to distinguish batches

8. Extension Suggestions

  • Custom MIME types (e.g. `application/json`)
  • Batch file sharing (observe size limits)
  • Multi-window scenarios with `setAnchor()`
  • Enhanced error handling and logging
  • Security validation before sharing

9. Conclusion

By combining QtOhosExtras::ShareKit, QOhosAbilityContext, and QOhosAppContext, Qt for HarmonyOS applications can seamlessly integrate system-level sharing capabilities. Developers can extend the provided examples to build consistent, secure, and controllable cross-application sharing experiences.