【问题标题】:Either use Loader's source or sourceComponent depending on <javascript expression>根据 <javascript 表达式> 使用 Loader 的源或源组件
【发布时间】:2018-12-29 12:03:11
【问题描述】:

我很难使用根据某些 javascript 表达式决定 sourcesourceComponent 的加载程序。我试过这个:

    Component {
        id: emptyComponent

        // for debugging, I would usually use Item {≠
        Rectangle {anchors.fill:parent; color: "red"}
    }

    Component {
        id: handStrengthColumnDelegate

        Loader {
            source: styleData.value !== undefined ? 'qrc:/resources/myDelegate.qml' : ''
            sourceComponent: styleData.value === undefined ? emptyComponent : undefined
        }
    }

我的想法是,用作表列的委托,我想在为相应行提供数据的情况下使用我的自定义委托,在没有数据的情况下使用空组件(这是一个不同种类的行,即一个类别)。

但是,似乎将sourceComponent 设置为undefined 会导致source 被忽略...我想要的是非/或 关系。

我可以将emptyComponent 移动到一个不同的文件中,或者我可以为myDelegate.qml 使用一个Loader 并且只使用sourceComponent,但是没有这种解决方法还有其他方法吗?

【问题讨论】:

    标签: javascript qml qt5


    【解决方案1】:

    引用Qt documentation for the Loader QML Type 关于source 属性:

    要卸载当前加载的对象,请将此属性设置为空字符串,或将 sourceComponent 设置为未定义。将 source 设置为新 URL 也会导致前一个 URL 创建的项目被卸载。

    这就是为什么将 sourceComponent 设置为 undefined 会导致 source 被忽略 - 它只是再次卸载组件。

    由于您的emptyComponent 为空(除了用于调试目的的矩形),您可以设置active 属性,而不是根据styleData.value 的值设置源。

    生成的 QML 如下所示:

    Component {
        id: handStrengthColumnDelegate
    
        Loader {
            source: 'qrc:/resources/myDelegate.qml'
            active: styleData.value !== undefined
        }
    }
    

    【讨论】:

    • 虽然没有显示,active 仍然会导致模型委托的评估。我仍然在 QML 控制台中遇到错误,因为它尝试访问未定义的 styleData 的属性。如果我根据styleData 选择myDelegate.qmlEmptyDelegate.qml,我不会收到错误...
    • @IceFire 在styleData.value === undefined 时有条件地将source 设置为空字符串怎么样?那么你甚至不需要使用active 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多