[英]QML: How to custom a component and use it in same file
Is there some syntax in QML to define and use a component in same file like this? 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
}
You can't really use an inline component directly, but you could use a loader:您不能真正直接使用内联组件,但可以使用加载器:
Component {
id: btn
Button { width = 100; height = 60; background = "red" }
}
Loader {
sourceComponent: btn
}
Another downside is this way you cannot directly specify properties for the created object.另一个缺点是这样你不能直接为创建的对象指定属性。
You can also use the component as a delegate for views and repeaters and such.您还可以将组件用作视图和中继器等的委托。
This is IMO one of the big omissions of QML.这是 IMO QML 的一大遗漏。
Update: I just noticed this answer a bit out of date.更新:我只是注意到这个答案有点过时了。 Qt has had inline components for a while.
Qt 内联组件已经有一段时间了。 Keep in mind they still have many bugs, there's stuff that will work in a regular component that will not work in an inlined one, especially around inline component properties in other inline components, property aliases and such.
请记住,它们仍然存在许多错误,有些东西可以在常规组件中工作,而在内联组件中不起作用,尤其是在其他内联组件中的内联组件属性、属性别名等方面。 If you get some weird behavior, just remember to test it out standalone as well:
如果您遇到一些奇怪的行为,请记住也要独立测试它:
component Custom : Item { ...new stuff... }
... in the same source
Custom { }
Also note that it has to be put inside some qml object, it cannot be just a source code global as with JS files.另请注意,它必须放在某个 qml 对象中,它不能像 JS 文件那样只是一个全局源代码。
Powered by @dtech由@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 }
}
}
And the result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.