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

标签 c++ qt qgraphicsitem

我重新定义了我自己的 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 轴,我会得到以下结果:
BoundingRec is black line

在其他位置我得到这个:

enter image description here

我需要这个:

enter image description here

有谁知道旋转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;
}

谢谢大家的回答!!

关于c++ - 来自 Qt 中具有倾斜度的线的 BoundingRec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006735/

相关文章:

c++ - 一种直接根据掩码转位的方法

c++ - 如何使用Qt画圆线形状?

c++ - QThreadPool maxThreadCount 在应用程序和 DLL 中不同

c++ - 图形场景中的 QMouseEvents 不起作用

c++ - 重叠的 QGraphicsItem-s 悬停事件

c++ - 从 QGraphicsScene 中删除 QGraphicsItem/QGraphicsObject?

c++ - 可以在 C++ 中将类声明为静态的吗?

c++ - 未到达的案例会影响切换案例的性能

c++ - 如何在 C++ 中比较两个 vector 的字符串内容

python - 当 QApplication 退出时,QT 引发段错误(核心已转储)