1

Qt5我对( PySide2) 和Qt4( )之间的行为差​​异感到困惑PySide。我得到的印象是Qt5有错误,但也许我做错了什么?

简而言之:当QPainterPath对 a 应用计算时QGraphicsPathItem(使用setPath),得到的大小QGraphicsPathItem比自身的大小QPainterPath1.5 个像素。这对我来说毫无意义,而 Qt4 的大小完全相同。

我提供了一段简单的代码来重现 PySide 和 PySide2。

使用 PySide:

#!/usr/bin/env python2

from PySide.QtCore import *
from PySide.QtGui import *

class Foo (QGraphicsPathItem):
    def __init__(self, parent):
        super(Foo, self).__init__()
        path = QPainterPath()
        path.addRect(0,0,10,10)
        print(str(path.boundingRect()))
        self.setPath(path)
        print(str(self.boundingRect()))

x=Foo(None)

结果是:

$ python2 ./with_py2.py 
PySide.QtCore.QRectF(0.000000, 0.000000, 10.000000, 10.000000)
PySide.QtCore.QRectF(0.000000, 0.000000, 10.000000, 10.000000)

大小相同,符合预期。都好。

与 Qt5 完全相同的代码:

#!/usr/bin/env python3

from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

class Foo (QGraphicsPathItem):
    def __init__(self, parent):
        super(Foo, self).__init__()
        path = QPainterPath()
        path.addRect(0,0,10,10)
        print(str(path.boundingRect()))
        self.setPath(path)
        print(str(self.boundingRect()))

x=Foo(None)

结果是:

$ python3 bug.py 
PySide2.QtCore.QRectF(0.000000, 0.000000, 10.000000, 10.000000)
PySide2.QtCore.QRectF(-0.500000, -0.500000, 11.000000, 11.000000)

有没有人看到任何明显的解释?

谢谢

4

1 回答 1

2

boundingRect 依赖于 QGraphicsPathItem 的 QPen 来计算它,如源代码中所示。

Qt4

QRectF QGraphicsPathItem::boundingRect() const
{
    Q_D(const QGraphicsPathItem);
    if (d->boundingRect.isNull()) {
        qreal pw = pen().widthF();
        if (pw == 0.0)
            d->boundingRect = d->path.controlPointRect();
        else {
            d->boundingRect = shape().controlPointRect();
        }
    }
    return d->boundingRect;
}

Qt5

QRectF QGraphicsPathItem::boundingRect() const
{
    Q_D(const QGraphicsPathItem);
    if (d->boundingRect.isNull()) {
        qreal pw = pen().style() == Qt::NoPen ? qreal(0) : pen().widthF();
        if (pw == 0.0)
            d->boundingRect = d->path.controlPointRect();
        else {
            d->boundingRect = shape().controlPointRect();
        }
    }
    return d->boundingRect;
}

如果您检查两个版本的 Qt 文档,您会发现默认创建的 QPen 的值发生了变化:

默认笔是纯黑色画笔,宽度为 0,方形帽样式 (Qt::SquareCap) 和斜角连接样式 (Qt::BevelJoin)。

(强调我的)

默认笔是纯黑色画笔,宽度为 1,方形帽样式 (Qt::SquareCap) 和斜角连接样式 (Qt::BevelJoin)。

(强调我的)

如果您想观察 PySide2 中的 PySide 行为,请将 a 设置QPen(Qt::NoPen)QGraphicsPathItem

class Foo(QGraphicsPathItem):
    def __init__(self, parent=None):
        super(Foo, self).__init__(parent)
        self.setPen(QPen(Qt.NoPen))
        path = QPainterPath()
        path.addRect(0, 0, 10, 10)
        print(str(path.boundingRect()))
        self.setPath(path)
        print(str(self.boundingRect()))


x = Foo()

输出

PySide2.QtCore.QRectF(0.000000, 0.000000, 10.000000, 10.000000)
PySide2.QtCore.QRectF(0.000000, 0.000000, 10.000000, 10.000000)
于 2019-11-06T20:22:19.783 回答