从 QML 文件中包含另一个 QML 文件 [英] Include another QML file from a QML file

查看:68
本文介绍了从 QML 文件中包含另一个 QML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stackoverflow 上有另一个关于这个问题的问题,但我没有找到可以接受的解决方案.所以我再问一次,因为老问题没有引起注意.

There's another question on Stackoverflow about this matter but I don't find the accepted solution possible. So I ask again because the old question is out of attention.

情况是这样的.我有由main.qml"、feature1.qml"、feature2.qml"定义的应用程序屏幕.

The situation is this way. I have application screens defined by 'main.qml', 'feature1.qml', 'feature2.qml'.

这些屏幕共享标题栏下方的相同工具栏.工具栏有多个项目,所以复制粘贴 QML 代码就像疯了一样.这个问题:QML 文件包含 - 或一个整体文件(结构 QML 代码)? 说可以只使用 QML 文件名作为组件名,但我无法让它工作.

These screens share the same toolbar below title bar. The toolbar has multiple items so copy-paste the QML code is like crazy. This question: QML file include - or one monolithic file (structure QML code)? says it's possible to just use QML file name as component name but I can't get it working.

有什么解决办法吗?请详细说明.

Any solution? with details pls.

推荐答案

假设您有一个名为 main.qml 的文件和另一个名为 MyCustomText.qml.如果两个文件在同一个目录下,你可以像这样直接加载组件:

Let's assume you have a file called main.qml and a component in another file called MyCustomText.qml. If both files are in the same directory you can directly load the component like this:

// in Main.qml
Rectangle {
  id: root
  MyCustomText {
    text: "This is my custom text element"
  }
}

如果 MyCustomText.qml 位于另一个子目录 MyComponents 例如要将所有自定义组件组合在一起,您首先需要 import 目录在以相同方式使用组件之前:

If MyCustomText.qml is in another subdirectory MyComponents for example to group all your custom components together, you first need to import the directory before using the component the same way:

// in Main.qml
import "MyComponents"

Rectangle {
  id: root
  MyCustomText {
    text: "This is my custom text element"
  }
}

另一个需要注意的重要事项是,如果您希望能够以这种方式使用它们,您的 QML 文件应该始终以大写字母开头

Another important thing to note is that your QML files should always start with an uppercase letter if you want to be able to use them this way

当然,您的 Loader 解决方案也可以,但这是在其他组件中导入 QML 文件的最简单方法.

Of course your Loader solution works too but this is the easiest way to import QML files in other components.

这篇关于从 QML 文件中包含另一个 QML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆