我已经重新定义了自己的QGraphicsItem以显示LineString。我重新定义了它,因为我需要创建自己的boundingbox,而painter重新定义了抽象方法。
现在我有这段代码:

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轴,则会得到以下结果:
c++ - 倾斜度为Qt的直线的BoundingRec-LMLPHP
在其他位置,我得到以下信息:
c++ - 倾斜度为Qt的直线的BoundingRec-LMLPHP
我需要这个:
c++ - 倾斜度为Qt的直线的BoundingRec-LMLPHP
有谁知道旋转boundinRec的任何方法吗?非常感谢!

最佳答案

我修复了重新定义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;
}

谢谢大家的回答!

10-08 08:05