繁体   English   中英

QML:如何自定义组件并在同一个文件中使用它

[英]QML: How to custom a component and use it in same file

QML 中是否有一些语法可以像这样在同一个文件中定义和使用组件?

import QtQuick 2.6
import QtQuick.Window 2.2

var MyButton = Rectangle { width : 100; height : 60; color : "red" } // define it

Window {
    visible: true
    MyButton // use it
}

您不能真正直接使用内联组件,但可以使用加载器:

Component {
  id: btn
  Button { width = 100; height = 60; background = "red" }
}

Loader {
  sourceComponent: btn
}

另一个缺点是这样你不能直接为创建的对象指定属性。

您还可以将组件用作视图和中继器等的委托。

这是 IMO QML 的一大遗漏。

更新:我只是注意到这个答案有点过时了。 Qt 内联组件已经有一段时间了。 请记住,它们仍然存在许多错误,有些东西可以在常规组件中工作,而在内联组件中不起作用,尤其是在其他内联组件中的内联组件属性、属性别名等方面。 如果您遇到一些奇怪的行为,请记住也要独立测试它:

component Custom : Item { ...new stuff... }
... in the same source
Custom { }

另请注意,它必须放在某个 qml 对象中,它不能像 JS 文件那样只是一个全局源代码。

由@dtech 提供支持

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Component { id: btn; Rectangle { width : 100; height : 100; color : "red" } }

    Column {
        spacing: 10
        Loader { sourceComponent: btn }
        Loader { sourceComponent: btn; width: 300 }
        Loader { sourceComponent: btn; width: 1000 }
    }
}

结果:

运行结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM