Android 中的 Fragment 与Qt Quick

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

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

在继续之前,建议先学习 Qt Academy 课程《Qt Academy:在 Android 应用中嵌入Qt Quick 3D 内容》。

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

  1. 找到你希望 QtQuickView 显示在其下的 Fragment 或 Activity。这里我们使用HomeFragment 和fragment_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. 为 QtQuickView 赋值,并使用以下方式将其与 Activity 实例关联:requireActivity()
    homeQtQuickView = QtQuickView(requireActivity())
    homeQmlContent = Screen01()
  6. 初始化布局参数。如果您通过编程方式创建视图、动态添加视图或在运行时更改视图,请执行此操作。否则,您可以跳过本节,且无需使用 `params ` 配合 `addView()`。
    val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                          ViewGroup.LayoutParams.MATCH_PARENT)
  7. 将视图添加到布局中,可通过以下方式实现:
    1. 在onCreateView() 中使用视图绑定:首先,通过在应用的build.gradle.kts文件的android部分中添加buildFeature 部分,确保已启用视图绑定:
      buildFeatures {
          viewBinding = true
      }

      然后在onCreateView() 中添加以下内容:

      binding = FragmentHomeBinding.inflate( inflater, container, false)
      homeQtQuickView.loadContent(homeQmlContent)
      
      val root: View = binding.root
      binding.homeQmlFrame.addView(homeQtQuickView, params)
      ...
      return root
    2. 在onCreate() 中使用findViewById() :
      val qtFrame = findViewById(R.id.qtFrame)
      qmlFrame.addView(m_quickView, params)
      m_quickView.loadContent(homeQmlContent)

      请参考其他Android 示例中Qt Quick 的用法。

您的Qt Quick 内容现在将显示在主片段中。

© 2026 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.