来自 Qt 中具有倾斜度的线的 BoundingRec

BoundingRec from a line with inclination in Qt

我重新定义了我自己的 QGraphicsItem 以显示一个 LineString。我重新定义了这个,因为我需要创建自己的 boundingbox 并且画家重新定义了抽象方法。

现在我有了这个代码:

QRectF myQGraphicsLine::boundingRect() const
{
    double lx = qMin(myLine->getX(0), myLine->getX(1));
    double rx = qMax(myLine->getX(0), myLine->getX(1));
    double ty = qMin(-myLine->getY(0), -myLine->getY(1));
    double by = qMax(-myLine->getY(0), -myLine->getY(1));
    return QRectF(lx-size/2,ty, rx -lx + size, by-ty).;
}

void myQGraphicsLine::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
    pen.setColor(Qt::red);
    
    QLine line(myLine->getX(0), -myLine->getY(0), myLine->getX(1), -myLine->getY(1));
    pen.setWidth(size);
    
    painter->setPen(pen);
    
    painter->setBrush(brush);
    painter->drawLine(line);
}

一切正常,但 boundingRec 有点问题。 如果这条线沿着 x 轴或 y 轴,我会得到这个结果:

在其他位置我得到这个:

我需要这个:

有谁知道旋转 boundinRec 的方法吗?非常感谢!

无法旋转 QRect 或 QRectf。它的边总是平行于垂直轴和水平轴。把它想象成一个点 (x, y) 给矩形的左上角加上 'width' 和 'height' 成员。无论您对 QRect 执行什么转换,它总是将 'width' 解释为水平距离,将 'height' 解释为垂直距离。

您可以将 QRect 的四个角提取为点,然后旋转这些点,但是无法将旋转后的点转换回 QRect,除非它们恰好平行于 viewport/window.

我修复了重新定义 QGraphicsItem::shape() 方法的问题。

为了使用这个,我用我的线形创建了一个 QPoligonF,在我的例子中我使用了这个函数:

void myQGraphicsLine::createSelectionPolygon()
{
    QPolygonF nPolygon;
    QLineF line(myLine->getX(0), -myLine->getY(0), myLine->getX(1), -myLine->getY(1));
    qreal radAngle = line.angle()* M_PI / 180;  //This the angle of my line vs X axe
    qreal dx = size/2 * sin(radAngle);
    qreal dy = size/2 * cos(radAngle);
    QPointF offset1 = QPointF(dx, dy);
    QPointF offset2 = QPointF(-dx, -dy);
    nPolygon << line.p1() + offset1
        << line.p1() + offset2
        << line.p2() + offset2
        << line.p2() + offset1;
    selectionPolygon = nPolygon;
    update();
}

paint()boundingRect()shape() 方法保持不变这个:

QRectF myQGraphicsLine::boundingRect() const
{
    return selectionPolygon.boundingRect();
}

void myQGraphicsLine::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
    pen.setColor(Qt::red);

    QLineF line(myLine->getX(0), -myLine->getY(0), myLine->getX(1), -myLine->getY(1));
    pen.setWidth(size);
    painter->setPen(pen);
    painter->setBrush(brush);
    painter->drawLine(line);
}

QPainterPath myQGraphicsLine::shape() const
{
    QPainterPath path;
    path.addPolygon(selectionPolygon);
    return path;
}

感谢大家的回答!!