【问题标题】:QML: Conditionally set different properties of a property groupQML:有条件地设置属性组的不同属性
【发布时间】:2014-10-02 15:52:35
【问题描述】:

如何一次性有条件地设置属性组的不同属性?

示例:假设有一个上下文属性_context.condition 可用。鉴于该值,我想为 qml 项目设置不同的锚点。

// Some item...
Rectangle {
    id: square
    width: 50
    height: 50

    // For simple properties this should work:
    color: { if (_context.condition) "blue"; else "red" }

    // But how to do it for complex properties like 'anchors'?
    // Note that I set different properties for different values of the condition.
    // Here is how I would do it, but this does not work:
    anchors: { 
        if (_context.condition) {
            // Anchors set 1:
            horizontalCenter: parent.horizontalCenter
            bottom: parent.bottom
            bottomMargin: 20
        } else {
            // Anchors set 2:
            verticalCenter: parent.verticalCenter
            right: parent.right
            rightMargin: 20
        }
    }
}

我在 Qt 5.3 中使用 QtQuick 2.0。谢谢!

【问题讨论】:

  • 看起来像 Horizo​​ntalCenter: _context.condition ? parent.horizo​​ntalCenter : 0 等等
  • 好吧,我不知道值 0 对应于“未设置”。我会检查一下。很麻烦,但至少有些东西。谢谢!
  • 实际上,我不确定这个,试试吧 :) 也许,你可以分配 'undefined' 而不是 0
  • 至少它适用于我的示例。发布正确的答案,您将获得学分! :)

标签: qt qml


【解决方案1】:

你可以试试这个(未测试):

anchors {
        horizontalCenter: _context.condition ? parent.horizontalCenter : undefined;
        bottom: _context.condition ? parent.bottom : undefined;
        bottomMargin: _context.condition ? 20 : undefined;
        verticalCenter: _context.condition ? undefined : parent.verticalCenter;    
        right: _context.condition ? undefined : parent.right;
        rightMargin: _context.condition ? undefined : 20;
        }

Resetting properties values

另外,根据this空花括号可以用来重置属性的值:

Item {
    property var first:  {}   // nothing = undefined
    property var second: {{}} // empty expression block = undefined
    property var third:  ({}) // empty object
}

【讨论】:

  • 我刚刚发现使用 '{}' 而不是 '0' 是一种更加类型中立的方式来表示“未定义”。除此之外,我会接受你的解决方案。
  • 我有更新链接到文档中准确描述锚点...请检查qt-project.org/doc/qt-5/…
猜你喜欢
  • 2022-11-18
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-01
相关资源
最近更新 更多