Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Qt Shift`QGraphicsTextItem`相对于文本中心的位置?_Qt_Qgraphicsitem - Fatal编程技术网

Qt Shift`QGraphicsTextItem`相对于文本中心的位置?

Qt Shift`QGraphicsTextItem`相对于文本中心的位置?,qt,qgraphicsitem,Qt,Qgraphicsitem,我有许多类继承自QGraphicsItem,它们以某种方式排列。为了简化计算,我以(0,0)为中心制作了场景和项目(使用boundingRect()具有+/-坐标) QGraphicsTextItem子类无法定义,它的pos()相对于左上角点 我已经尝试了很多方法来移动它,使其位于文本中心(例如,建议的解决方案-引用的代码实际上剪切了我的文本,并且只显示左下角的四分之一) 我认为解决方案应该很简单,比如 void TextItem::paint(QPainter* painter, const

我有许多类继承自
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()
的一个实验:


我必须改变初始位置以及调整大小,以触发新位置-我无法在paint()中执行此操作,因为从一开始我就认为,任何重新绘制都会不断重新计算位置

仅需要调整初始位置-但随着字体大小(或样式…)的更改,其边框也会更改,因此必须根据以前的位置重新计算位置

在构造函数中

setPos(- boundingRect().width()/2, - boundingRect().height()/2);
在修改项目(字体)大小的函数中

我认为如果重写paint(),还必须重写boundingRect(),以便绘制的文本位于boundingRect()返回的矩形中。我尝试过,当我尝试“翻译”
boundingRect()
时,我最终得到了一个截断文本。。。(有关代码,请参见编辑)
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));
    }
}