gpt4 book ai didi

qt - 应用 QGraphicsItem::ItemIgnoresTransformations 后保持相对子位置

转载 作者:行者123 更新时间:2023-12-04 07:06:42 26 4
gpt4 key购买 nike

我有一个 QGraphicsTextItem 的父级 QGraphicsItem。我希望 QGraphicsTextItem 始终位于 QGraphicsItem 的正上方,但我也希望文本在比例因子低于 1 时保持相同的大小,即即使父图形,文本仍保持比例因子为 1 的大小项目被缩小。我发现设置 QGraphicsItem::ItemIgnoresTransformations当比例因子低于 1 时,标志为 true 可以保持大小。

但我似乎无法找到一种方法让文本的位置始终保持在 QGraphicsItem 上方。有没有办法做到这一点?我尝试使用 deviceTransform ()功能,但是当我滚动出来时,文本仍然从 QGraphicsItem 移开。更糟糕的是,一些文本项目开始“摇晃”,即它们开始不断地轻微改变它们的位置,以至于它们看起来像是在晃动。如果这是我需要使用的功能,我想我不知道如何正确使用它。

在我的 QGraphicsItem 的构造函数中,我添加了一个 QGraphicsTextItem:

fTextItem = new QGraphicsTextItem(getName(), this);
fTextItem->setFlag(QGraphicsItem::ItemIgnoresTransformations);

这是 QGraphicsItem 的绘制函数的代码片段
qreal lod = painter->worldTransform().m22();
if(lod <= 1.0) {
fTextItem-setFlag(QGraphicsItem::ItemIgnoresTransformations);
fTextItem->setPos(fTextItem->deviceTransform(view-viewportTransform()).inverted().map(view->mapFromScene(mapToScene(0,0))));
} else {
fTextItem->setFlag(QGraphicsItem::ItemIgnoresTransformations, false);
fTextItem->setPos(0, 0);
}

最佳答案

免责声明:这对于您正在尝试做的事情来说可能有点矫枉过正。我们的项目中有一些额外的限制,使这个解决方案对我们来说是最简单的。

我们不得不在一个项目中做类似的事情,结果我们最容易不使用 ItemIgnoresTransformations而是滚动我们自己的转换。这是我们用来创建仅平移(无缩放)变换以在特定位置绘制项目的主要函数。您可以根据自己的使用情况对其进行修改。

static QTransform GenerateTranslationOnlyTransform(
const QTransform &original_transform,
const QPointF &target_point) {
// To draw the unscaled icons, we desire a transform with scaling factors
// of 1 and shearing factors of 0 and the appropriate translation such that
// our icon center ends up at the same point. According to the
// documentation, QTransform transforms a point in the plane to another
// point using the following formulas:
// x' = m11*x + m21*y + dx
// y' = m22*y + m12*x + dy
//
// For our new transform, m11 and m22 (scaling) are 1, and m21 and m12
// (shearing) are 0. Since we want x' and y' to be the same, we have the
// following equations:
// m11*x + m21*y + dx = x + dx[new]
// m22*y + m12*x + dy = y + dy[new]
//
// Thus,
// dx[new] = m11*x - x + m21*y + dx
// dy[new] = m22*y - y + m12*x + dy
qreal dx = original_transform.m11() * target_point.x()
- target_point.x()
+ original_transform.m21() * target_point.y()
+ original_transform.m31();
qreal dy = original_transform.m22() * target_point.y()
- target_point.y()
+ original_transform.m12() * target_point.x()
+ original_transform.m32();

return QTransform::fromTranslate(dx, dy);
}

要使用,请取 QPainter传递给paint方法的转换并执行以下操作:
painter->save();
painter->setTransform(GenerateTranslationOnlyTransform(painter->transform(),
some_point));
// Draw your item.
painter->restore();

关于qt - 应用 QGraphicsItem::ItemIgnoresTransformations 后保持相对子位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com