我遇到了同样的问题,我花了一段时间才弄清楚。我就是这样解决的。
扩展一个 QGraphicsItem 类,覆盖paint()。
在paint()内部,将变换的缩放因子重置为1(即m11和m22),并保存重置前的m11(x缩放因子)和m22(y缩放因子)。
然后,像往常一样绘制,但将 x 与 m11 相乘,将 y 与 m22 相乘。这避免了使用默认变换进行绘制,而是根据场景的变换显式计算位置。
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget)
{
QTransform t = painter->transform();
qreal m11 = t.m11(), m22 = t.m22();
painter->save(); // save painter state
painter->setTransform(QTransform(1, t.m12(), t.m13(),
t.m21(), 1, t.m23(), t.m31(),
t.m32(), t.m33()));
int x = 0, y = 0; // item's coordinates
painter->drawText(x*m11, y*m22, "Text"); // the text itself will not be scaled, but when the scene is transformed, this text will still anchor correctly
painter->restore(); // restore painter state
}
以下代码块使用默认转换进行绘制
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget)
{
int x = 0, y = 0;
painter->drawText(x, y, "Text");
}
您可以尝试两者来查看差异。希望这会有所帮助。