使用Qt Quick for Android 制作 Android 碎片

通过使用基于 ViewGroup 的对象,您可以在 Android UI 布局中使用QtQuickView。这里我们将使用FrameLayout

如果你不熟悉QtQuickViewAPI,请在继续本教程之前阅读其文档。

首先,使用Bottom Navigation Views Activity 模板在 Android Studio 中创建一个新项目。

  1. 找到你想让 QtQuickView 可见的片段或活动。这里我们使用HomeFragmentfragment_home.xml
  2. fragment_home.xml 中创建一个 FrameLayout 并设置其id ,如下所示。
    <FrameLayout
    android:id="@+id/homeQmlFrame"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHeight_percent="0.8"/>

    请注意这个 id,因为在绑定布局时需要在HomeFragment 中引用它。

  3. 在 HomeFragment.kt 中,为 FrameLayout 添加导入语句:
    import android.widget.FrameLayout
  4. QtQuickView和 Screen01 QML 类型添加导入,并在类中声明:
    import org.qtproject.qt.android.QtQuickView
    import org.qtproject.example.RoboApp.RoboContent.Screen01
    
    class HomeFragment : Fragment() {
    
    private var binding: FragmentHomeBinding? = null
    private lateinit var homeQmlContent: Screen01
    private lateinit var homeQtQuickView: QtQuickView
  5. 在重载的onCreateView() 函数中:
    1. 分配你的 QtQuickView,使用this.Activity
      homeQtQuickView = QtQuickView(this.activity)
      homeQmlContent = Screen01()
    2. 使用FrameLayout.LayoutParams初始化布局参数
      val params = FrameLayout.LayoutParams(
         ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
      
      binding = FragmentHomeBinding.inflate(inflater, container, false)
      val root: View = binding.root
      \li Add it to the layout:
      \code
      binding.homeQmlFrame.addView(homeQtQuickView, params)
    3. 加载 QML 内容:
      homeQtQuickView.loadContent(homeQmlContent)
      return root

现在,您的Qt Quick 内容将出现在您的主页片段中。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.