防止QGraphicsItem中的字体缩放

4
我正在使用 QGraphicsTextItem 在场景上绘制文本。文本沿着路径(QGraphicsPathItem)绘制,该路径是我 QGraphicsTextItem 的父级 - 因此,文本旋转变为沿着路径元素,并且在缩放视图时固定在其上。但是,QGraphicsTextItem 的字体大小也会随着缩放视图而更改 - 这就是我试图避免的。如果我将 QGraphicsItem :: ItemIgnoresTransformations 标志设置为 QGraphicsTextItem ,则它会停止旋转,而其父级 (QGraphicsPathItem ) 则会继续旋转。

enter image description here

我明白我必须重新实现 QGraphicsTextItem :: paint 函数,但是我卡在了坐标系上。 以下是代码(Label 类公开继承 QGraphicsTextItem):

void Label::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget )
{
    // Store current position and rotation
    QPointF position = pos();
    qreal angle = rotation();

    // Store current transformation matrix
    QTransform transform = painter->worldTransform();

    // Reset painter transformation
    painter->setTransform( QTransform() );

    // Rotate painter to the stored angle
    painter->rotate( angle );

    // Draw the text
    painter->drawText( mapToScene( position ), toPlainText() );

    // Restore transformation matrix
    painter->setTransform( transform );
}

我的文字在屏幕上的位置(和旋转)是不可预测的 :( 我做错了什么?非常感谢您提前。


2
我在使用QGraphicsTextItem时遇到了类似的问题:忽略变换会导致位置在不同视图比例下出现明显的偏移。我认为居中可能会解决这个问题。 - handle
3个回答

3
我这样解决了一个问题——为了绘制一条线/圆/矩形/路径,我希望它被转换,我使用相应的QGraphicsLine/Ellipse/Rect/PathItem。为了绘制文本(我不希望其被转换),我使用QGraphicsSimpleTextItem。我将文本设置为忽略转换,并将其父项设置为线/椭圆形/矩形/路径项。线/椭圆形/矩形/路径项会变换,但文本不会——这正是我想要的。我还可以旋转文本并设置其位置。 谢谢您的回答。

1
我曾经遇到过这个问题。与其忽略变换,你需要在放大功能中缩小那些不想被放大的项。当你放大时,如果你改变了比例尺,例如ds,请将项目按1.0 / ds进行缩放。你可能需要改变它们的位置。希望这可以帮助你。编辑:我希望我正确理解了问题。

1
以下解决方案完美地适用于我:
void MyDerivedQGraphicsItem::paint(QPainter *painter, const StyleOptionGraphicsItem *option, QWidget *widget)
{
    double scaleValue = scale()/painter->transform().m11();
    painter->save();
    painter->scale(scaleValue, scaleValue);
    painter->drawText(...);
    painter->restore();
    ...
}

我们还可以将scaleValue乘以其他我们想要保持其大小不变的尺寸,以便在保存/恢复环境之外保持其大小不变。
QPointF ref(500, 500);
QPointF vector = scaleValue * QPointF(100, 100);
painter->drawLine(ref+vector, ref-vector);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接