8

我有一个 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);
}
4

6 回答 6

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());
于 2012-09-20T00:29:29.367 回答
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);
}

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

painter->save();
painter->setTransform(GenerateTranslationOnlyTransform(painter->transform(),
                                                       some_point));
// Draw your item.
painter->restore();
于 2012-07-12T20:11:37.653 回答
1

戴夫·马特(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;
}

使用此解决方案,该项目在我的情况下工作得很好。

于 2014-05-20T09:14:33.363 回答
1

我找到了另一种解决方案,它不涉及弄乱任何转换或手动缩放/定位。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;
};
于 2017-02-08T13:49:53.247 回答
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)); 
于 2014-03-26T04:17:34.697 回答
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
于 2014-08-03T19:11:08.550 回答