应用QGraphicsItem :: ItemIgnoresTransformations后维护相对子位置

时间:2012-07-12 19:34:52

标签: qt qt4 qgraphicsview

我有一个QGraphicsTextItem是QGraphicsItem的父级。我希望QGraphicsTextItem始终位于QGraphicsItem的正上方,但我还希望当比例因子低于1时文本保持相同的大小,即文本保持其比例因子为1时的大小,即使父图形也是如此item缩小了。我发现当比例因子小于1时将QGraphicsItem::ItemIgnoresTransformations标志设置为true可以保留大小。

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

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

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

以下是QGraphicsItem

的paint函数的代码片段
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);
}

6 个答案:

答案 0 :(得分:6)

我的建议是以这种方式继承QGraphicsSimpleTextItem:

class TextItem
    : public QGraphicsSimpleTextItem
{
public:
    TextItem(const QString &text)
        : QGraphicsSimpleTextItem(text)
    {

    }
    void paint(QPainter *painter, 
        const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        painter->translate(boundingRect().topLeft());
        QGraphicsSimpleTextItem::paint(painter, option, widget);
        painter->translate(-boundingRect().topLeft());
    }
    QRectF boundingRect() const
    {
        QRectF b = QGraphicsSimpleTextItem::boundingRect();
        return QRectF(b.x()-b.width()/2.0, b.y()-b.height()/2.0, 
            b.width(), b.height());
    }
};
QGraphicsSimpleTextItem *mText = new TextItem("Item");
scene()->addItem(mText);
mText->setFlag(QGraphicsItem::ItemIgnoresTransformations, true);
mText->setPos(itemToFollow->pos());

答案 1 :(得分:4)

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

我们必须在一个项目中做类似的事情,最后我们最简单的方法是不使用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);
}

要使用,请将传递给paint方法的QPainter转换执行以下操作:

painter->save();
painter->setTransform(GenerateTranslationOnlyTransform(painter->transform(),
                                                       some_point));
// Draw your item.
painter->restore();

答案 2 :(得分:0)

添加Dave Mateer的答案,我认为在某些情况下添加它还有助于您还应该维护对象的正确边界矩形(以及形状)。对我来说,我需要稍微修改boundingRect()以获得正确的对象选择行为。请记住,如果我们不使用ItemIgnoresTransformations标志,则会像往常一样缩放和转换对象的边界矩形。所以我们还需要重新调整boundingRect以保持视图独立性效果。

要保持与视图无关的边界矩形变得非常简单:只需从deviceTransform(m_view->viewportTransform()).inverted().m11()获取缩放因子,然后将此常量乘以局部坐标边界矩形。例如:

qreal m = this->deviceTransform(m_view->viewportTransform()).inverted().m11();
return QRectF(m*(m_shapeX), m*(m_shapeY),
              m*(m_shapeR), m*(m_shapeR)); 

答案 3 :(得分:0)

Dave Mateer的精彩回答!我有一个问题,我想在不同的缩放级别定义一个不同的比例因子。我就这样做了:

void MyGraphicsItem::paint(QPainter * painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
    //save painter for later operations
    painter->save();
    QTransform originalTransform = painter->transform();
    QPointF originalCenter = rect().center();
    qreal dx = originalTransform.m11() * originalCenter.x() + originalTransform.m21() * originalCenter.y() + originalTransform.m31();
    qreal dy = originalTransform.m22() * originalCenter.y() + originalTransform.m12() * originalCenter.x() + originalTransform.m32();
    //normally our target scale factor is 1, meaning the item has keeps its size, regardless of zoom
    //we adjust the scale factor though when the item is smaller than one pixel in comparison to the background image
    qreal factor = 1.0;
    //check if scale factor if bigger that the item size, and thus it occupies less that a pixel in comparision to the background image
    if (rect().width() < originalTransform.m11()) {
        //calculate adjusted scale factor
        factor = originalTransform.m11() / rect().width();
    }
    //adjust position according to scale factor
    dx -= factor * originalCenter.x();
    dy -= factor * originalCenter.y();
    //set the new transform for painting
    painter->setTransform(QTransform::fromScale(factor, factor) * QTransform::fromTranslate(dx, dy));
    //now paint...
    QGraphicsXYZItem::paint(painter, option, widget);
    //restore original painter
    painter->restore();
}

在这种情况下你也需要调整边界矩形:

QRectF MyGraphicsItem::boundingRect() const
{
    QRectF rect = QGraphicsEllipseItem::boundingRect();
    //this is a bit hackish, let me know if you know another way...
    if (scene() != NULL && scene()->views().at(0) != NULL)
    {
        //get viewport transform
        QTransform itemTransform = scene()->views().at(0)->transform();
        QPointF originalCenter = rect.center();
        //calculate back-projected original size of item
        qreal realSizeX = rect.width() / itemTransform.m11();
        qreal realSizeY = rect.height() / itemTransform.m11();
        //check if scale factor is bigger that the item size, and thus it occupies less that a pixel in comparison 
        //to the background image and adjust size back to equivalent of 1 pixel
        realSizeX = realSizeX < 1.0 ? 1.0 : realSizeX;
        realSizeY = realSizeY < 1.0 ? 1.0 : realSizeY;
        //set adjusted position and size according to scale factor
        rect = QRectF(rect.center().x() - realSizeX / 2.0, rect.center().y() - realSizeY / 2.0, realSizeX, realSizeY);
    }
    return rect;
}

使用此解决方案,该项目在我的案例中运作良好。

答案 4 :(得分:0)

这是我设计的非常复杂的解决方案:

1)获取父级的boundingRect()并将其映射到场景 2)取这个点列表的最小X和Y,这是你的项目的真实原点,在场景坐标中 3)设置孩子的位置

在Pyside:

    br = parent.mapToScene(parent.boundingRect())
    realX = min([item.x() for item in br])
    realY = min([item.y() for item in br])
    child.setPos(parent.mapFromScene(realX, realY)) #modify according to need

答案 5 :(得分:0)

我找到了另一种解决方案,它不涉及任何变换或手动缩放/定位。 QGraphicsItem::ItemIgnoresTransformations标志描述中有一个提示:

  

QGraphicsItem::ItemIgnoresTransformations

     

该项忽略继承的转换(即其位置为   仍锚定到其父,但父或视图旋转,缩放或   剪切变换被忽略)。 [...]

这就是关键!我们需要两个项目:一个保持相对位置的父级(没有设置任何标志)和一个子项目,它将在父级的(0,0)点(用QGraphicsItem::ItemIgnoresTransformations进行绘图国旗集)。就这么简单!

我已将此功能封装到一个类中 - 这是一些代码:

#include <QGraphicsItem>
#include <QPainter>

class SampleShape : public QGraphicsItem
{
private:
    /* This class implements shape drawing */
    class SampleShapeImpl : public QGraphicsItem
    {
    public:
        SampleShapeImpl (qreal len, QGraphicsItem *parent = nullptr)
            : QGraphicsItem(parent), m_len(len)
        {
            /* ignore transformations (!) */
            setFlag(QGraphicsItem::ItemIgnoresTransformations);
        }

        QRectF boundingRect (void) const override
        {
            /* sample bounding rectangle */
            return QRectF(-m_len, -m_len, m_len*2, m_len*2);
        }

        void paint (QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override
        {
            /* draw a shape, (0,0) is an anchor */
            painter->drawLine(0, -m_len, 0, m_len);
            painter->drawLine(-m_len, 0, m_len, 0);
            // ...
        }

    private:
        qreal m_len;  // sample shape parameter
    };

public:
    /* This is actually almost an empty class, you only need to set
     * a position and pass any parameters to a SampleShapeImpl class.
     */
    SampleShape (qreal x, qreal y, qreal len, QGraphicsItem *parent = nullptr)
        : QGraphicsItem(parent), m_impl(len, this) // <-- IMPORTANT!!!
    {
        /* set position at (x, y), view transformations will apply */
        setPos(x, y);
    }

    QRectF boundingRect (void) const override
    {
        return QRectF(); // it's just a point, no size
    }

    void paint (QPainter *, const QStyleOptionGraphicsItem *, QWidget *) override
    {
        // empty, drawing is done in SampleShapeImpl
    }

private:
    SampleShapeImpl m_impl;
};