【问题标题】:QML: How to custom a component and use it in same fileQML:如何自定义组件并在同一个文件中使用它
【发布时间】:2017-11-21 02:37:26
【问题描述】:

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
}

【问题讨论】:

    标签: qt user-interface qml qtquick2


    【解决方案1】:

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

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

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

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

    这是 IMO QML 的一大遗漏。

    【讨论】:

    • 成功了。我可以自定义按钮宽度。请参阅我在此问题下方的捕获。
    • 这个技巧适用于大小,因为项目将在特定情况下填充加载器,但仅此而已。例如,您不能直接设置信号处理程序,您必须使用 Connections 元素。
    【解决方案2】:

    由@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 }
        }
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2020-10-28
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      相关资源
      最近更新 更多