QGraphicsItem.setTransformations不能按预期工作(也:PySide2与PyQt5之间的差异)

问题描述 投票:1回答:1

[当我尝试将转换添加到QGraphicsItem时,它没有显示在该对象的转换列表中:

from PySide2.QtWidgets import QGraphicsRectItem, QGraphicsScale

rect = QGraphicsRectItem()
rect.setTransformations([QGraphicsScale()])
n = len(rect.transformations())
assert n == 1, f'object has {n} transformations (expecting 1)'
# AssertionError: object has 0 transformations (expecting 1)    

[让我感到惊讶的是,使用PyQt5完全相同的代码可以正常工作。

from PyQt5.QtWidgets import QGraphicsRectItem, QGraphicsScale
...
# No AssertionError

PyQt5与PySide2之间的差异是什么,这是PySide2中的错误还是我使用PySide2错误?在后一种情况下,如何解决问题,并以适用于两个软件包的方式获得奖励积分?

python pyqt pyqt5 pyside2 qgraphicsitem
1个回答
1
投票

要知道哪个是正确的,那么必须分析原始来源的行为:

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsRectItem rect;
    rect.setTransformations({new QGraphicsScale()});
    int n = rect.transformations().length();
    char message[80];
    sprintf(message, "object has %d transformations (expecting 1)", n);
    Q_ASSERT_X(n == 1, "QGraphicsItem::setTransformations()", message);
}

并且在执行该错误时,不会释放该错误,因此PyQt5具有适当的行为。

对于PySide2,在处理未分配给变量的对象时会遇到问题,在这种情况下,解决方案是将列表分配给变量:

from PySide2.QtWidgets import QGraphicsRectItem, QGraphicsScale

rect = QGraphicsRectItem()
transforms = [QGraphicsScale()]
rect.setTransformations(transforms)
n = len(rect.transformations())
assert n == 1, f"object has {n} transformations (expecting 1)"
© www.soinside.com 2019 - 2024. All rights reserved.