我工作了很长时间,QGraphicsItem它有transform()功能.现在我不会做同样的事情,QQuickItem但不幸的是它错过了transform().所以我的问题 - 如何获得变换矩阵QQuickItem?
实际上QQuickItem提供了transform()方法,但它返回分配给给定项的所有转换的列表.这是因为可以将多个转换分配给单个转换Item.返回类型QQuickItem::transform是QQmlListProperty<QQuickTransform>- 它是QML list<Transform>类型的包装器(请参阅Item的文档).它可以迭代,产生QQuickTransform *元素.QQuickTransform是转换的基类,它提供了一个applyTo接受QMatrix4x4 *参数并在其上应用转换的虚方法.
QML允许实例化几个QQuickTransform子类(用于转换,旋转和缩放),并允许用户定义自定义转换(例如,用于偏斜).
要获得所需的单个变换矩阵,必须从单位矩阵开始,然后依次应用给定的所有变换QQuickItem.
QMatrix4x4 transformOfItem(QQuickItem *item)
{
QQmlListProperty transformations = item->transform();
const int count = transformations.count(&transformations);
// Prepare result structure, it will be default-initialized to be an identity matrix
QMatrix4x4 transformMatrix;
// Apply sequentially all transformation from the item
for(int i = 0; i applyTo(&transformMatrix);
}
return transformMatrix;
}
请注意,该函数返回一个转换矩阵QMatrix4x4- 它比QTransform基于3x3转换矩阵的旧转换更旧,因此无法在没有丢失的情况下进行转换.如果你愿意,你可以使用QMatrix4x4::toAffine获得的QMatrix(3×3),并用它来创建QTransform对象.但是,如果您的QQuickItem转换包含非关联元素,它们将会丢失.
还有一点需要注意:我发布的方法仅适用于通过赋值给transform属性定义的转换.它不检查scale和rotation属性.如果使用它们,则应使用适当的QQuickItem方法检查其值,并调整返回的矩阵以包含这两个额外的转换.