Di chuyển PySide6 lên nền tảng Android

Người viết không thể cung cấp bản dịch hoàn chỉnh vì yêu cầu kỹ thuật cao. Bài viết gốc (trong tiếng Trung) có thể tham khảo tại: https://www.qt.io/blog/taking-qt-for-python-to-android

Yêu cầu hệ điều hành Linux

Cài đặt môi trường Qt

Tải về trình cài đặt trực tuyến từ: http://mirrors.ustc.edu.cn/qtproject/official_releases/online_installers/

Phiên bản mới (4.0.1-1 trở lên) hỗ trợ tham số --mirror. Ví dụ trên Windows: .\qt-unified-windows-x86-online.exe --mirror https://mirrors.ustc.edu.cn/qtproject

Cần cài thêm LLVM (khoảng 2.22GB)

Cấu hình phát triển Android

Cài JDK 11 trở lên

Tải công cụ Command Line Tools (liên kết cá nhân có thể khác)

Ví dụ script cài đặt:

#!/bin/bash
if [ -z "$1" ]; then
    echo "Chưa cung cấp đường dẫn file .zip"
    exit 1
fi
SDK_DIR="$PWD/android_sdk"
mkdir -p "$SDK_DIR"
unzip "$1" -d "$SDK_DIR"
"$SDK_DIR/cmdline-tools/latest/bin/sdkmanager" "ndk;25.2.9519653" "build-tools;33.0.2" "platforms;android-31"

Đặt biến môi trường:

export ANDROID_SDK_ROOT="android_sdk"
export ANDROID_NDK_ROOT="android_sdk/ndk/25.2.9519653"

Biên dịch wheel cho Android

Tải mã nguồn PySide6 hoặc sử dụng phiên bản đã chỉnh sửa

Cài phụ thuộc:

cd pyside-source/
pip install -r tools/cross_compile_android/requirements.txt
pip install -r requirements.txt

Chạy biên dịch:

python tools/cross_compile_android/main.py --plat-name=aarch64 --ndk-path=$ANDROID_NDK_ROOT --qt-path=ĐƯỜNG_DẪN_QT --sdk-path=$ANDROID_SDK_ROOT

Lưu ý gỡ lỗi

Sửa script để giữ lại logs:

# Bản sửa đổi chính
import os
import shutil

def create_build_dir():
    build_dir = "/tmp/build_logs"
    if not os.path.exists(build_dir):
        os.makedirs(build_dir)
    return build_dir

# Trong quá trình biên dịch:
log_file = os.path.join(create_build_dir(), "compile.log")
with open(log_file, "w") as f:
    subprocess.run(command, stdout=f, stderr=f)

Giải quyết lỗi tài liệu

Kích hoạt tạo tài liệu bằng cách thêm:

qfp_ccompile_cmd.extend(["--build-docs"])

Cài gói cần thiết:

pip install sphinx sphinx-design myst-parser

Lỗi 'invalid command'

Sửa file setuptools bằng cách:

  1. Tìm dòng setup()
  2. Thêm from setuptools import setup nếu chưa có

Kết quả biên dịch

Thu được 2 file:

  • PySide6-6.5.2-cp37-abi3-android_aarch64.whl
  • shiboken6-6.5.2-cp37-abi3-android_aarch64.whl

Tạo APK

Tạo thư mục chứa:

  • main.py (chương trình chính)
  • 2 file wheel trên

Chạy lệnh:

pyside6-android-deploy --wheel-pyside=PySide6-... --wheel-shiboken=shiboken6-... --name=test_app

Lỗi phổ biến

Cài phiên bản cụ thể của thư viện sh:

pip install sh==1.14.2

Sử dụng phiên bản python_for_android đã chỉnh sửa (loại bỏ phụ thuộc không cần thiết)

Thẻ: PySide6 Android Qt NDK Cross-Compile

Đăng vào ngày 20 tháng 6 lúc 04:51