gpt4 book ai didi

qt - QML:有条件地设置属性组的不同属性

转载 作者:行者123 更新时间:2023-12-03 07:08:52 28 4
gpt4 key购买 nike

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

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

// 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。谢谢!

最佳答案

您可以尝试这个(未测试):

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
}

关于qt - QML:有条件地设置属性组的不同属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26164645/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com