我有许多继承自QGraphicsItem
的类,它们以某种方式排列。为了简化计算,我将场景和项目以 (0, 0) 为中心(boundingRect()
具有 +/- 坐标)。
QGraphicsTextItem
子类违背了我的要求,它的 pos()
是相对于左上角的点。
我尝试了多种方法来移动它,使其居中于文本中心(例如,建议的解决方案 here - 引用的代码实际上剪切了我的文本,仅显示左下四分之一)。
我认为解决方案应该很简单,例如
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));
}
}
关于qt - 相对于文本中心移动 `QGraphicsTextItem` 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30037429/