移动`QgraphicStextItem`相对于文本中心的位置



我有许多从 QGraphicsItem继承的类,可以以某种方式安排。为了简化计算,我制作了以(0,0)为中心的场景和项目(boundingRect()具有/-坐标)。

QGraphicsTextItem子类违背我,它的 pos()是相对于左上点的。

我已经尝试了许多事情来移动它,因此它以文本中心为中心(例如,建议的解决方案 - 所引用的代码实际上剪切了我的文本,仅显示左下季度)。

我想象解决方案应该是简单的,例如

void TextItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
    painter->translate( -boundingRect().width()/2.0, -boundingRect().height()/2.0 );
    QGraphicsTextItem::paint(painter, option, widget );    
}

上面的"有效"工作 - 但是随着我增加项目比例 ->增加字体,显示的项目被切断...

我试图设置pos()-但问题是,我仍然需要跟踪场景中的实际位置,所以我不能只是替换它。

略有不愉快的副作用 - 居中元件上的QGraphicsView也不起作用。

如何使我的QGraphicsTextItem显示其相对于文本中心的位置?

编辑:更改boundingRect()的实验之一:

QRectF TextItem::boundingRect() const
{
    QRectF rect = QGraphicsTextItem::boundingRect();
    rect.translate(QPointF(-rect.width()/2.0, -rect.height()/2.0));
    return rect;
}

我不得不移动初始位置以及调整大小以触发一个新的位置 - 我无法在Paint()中做到这一点,因为正如我从一开始,任何重新粉刷都会不断重新计算位置。

仅需要调整初始位置 - 但是随着字体大小(或样式...)的变化,其边界矩形也会更改,因此必须根据先前的位置重新计算该位置。

在构造函数中,

setPos(- boundingRect().width()/2, - boundingRect().height()/2);

在修改项目(字体)大小的函数中,

void TextItem::setSize(int s)
{
    QRectF oldRect = boundingRect();
    QFont f;
    f.setPointSize(s);
    setFont(f);
    if(m_scale != s)
    {
        m_scale = s;
        qreal x = pos().x() - boundingRect().width()/2.0 + oldRect.width()/2.0;
        qreal y = pos().y() - boundingRect().height()/2.0 + oldRect.height()/2.0;
        setPos(QPointF(x, y));
    }
}

最新更新