简体   繁体   English

如何使用 QGraphicsItem::setPos() function

[英]How to use the QGraphicsItem::setPos() function

I can't figure out how the setPos() function of the QGraphicsItem class works.我无法弄清楚QGraphicsItem class 的setPos() function 是如何工作的。

My Rect class has no parent, so its origin is relative to the scene.我的Rect class 没有父级,所以它的原点是相对于场景的。

I try to put the rectangle back at (0, 0) after it is moved with the mouse but it is placed in a different place depending on where I had moved it.在用鼠标移动矩形后,我尝试将矩形放回 (0, 0),但根据我移动它的位置,它被放置在不同的位置。 I suppose that means that the origin of the scene moves but what causes this change?我想这意味着场景的原点移动了,但是是什么导致了这种变化?

class Rect : public QGraphicsItem {
public:
    Rect(): QGraphicsItem()
    {
        setFlag(ItemIsMovable);
    }

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
    {
        painter->drawRect(0, 0, 20, 20);
    }

    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
    {
            setPos(0, 0);
            update();
            QGraphicsItem::mouseReleaseEvent(event);
    }

    QRectF boundingRect() const
    {
            return QRectF(0, 0, 20, 20);
    }

private:
};
int main(int argc, char *argv[])
{
        QApplication a(argc, argv);
        QGraphicsScene scene;
        QGraphicsView view(&scene);
        Rect obj;
        scene.addItem(&obj);

        view.show();
        return a.exec();
}

When you create a QGraphicsView you initially accept the default settings.当您创建 QGraphicsView 时,您最初接受默认设置。 A standard setting is, for example, that it is horizontally centered.例如,标准设置是水平居中。

在此处输入图像描述

Another factor is that the default area size is probably up to the maximum size.另一个因素是默认区域大小可能达到最大大小。

what you can do set a custom size for the scene.您可以为场景设置自定义大小。 You do that with graphicsView->setSceneRect(0,0,300,300);您可以使用graphicsView->setSceneRect(0,0,300,300); (for example) (例如)

    scene       = new QGraphicsScene(this);
    
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setRenderHint(QPainter::Antialiasing);
    ui->graphicsView->setSceneRect(0,0, 300,300);
    
    rectItem    = new QGraphicsRectItem(0,0, 100, 100);
    rectItem->setPen(QPen(Qt::darkMagenta, 2));
    rectItem->setBrush(QGradient(QGradient::SaintPetersburg));
    rectItem->setPos(190,10);

    scene->addItem(rectItem);

在此处输入图像描述 在此处输入图像描述

So in summary: if you want to work with fixed values.总而言之:如果您想使用固定值。 maybe it is better to know the total size.也许最好知道总大小。 (that was not clear from your code, that's why I gave this example) (从你的代码中不清楚,这就是我给出这个例子的原因)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM