I want to make one QGraphicsItem
in a QGraphicsScene
move (or change size) when another one moves. But, trying to access either QGraphicsItem
from the QGraphicsScene
object causes crashes.
我想在一个QGraphicsScene移动(或更改大小)的一个QGraphicsItem当另一个移动。但是,尝试从QGraphicsScene对象中访问QGraphicsItem会导致崩溃。
Here's a dummy example. I want to automatically:
这是一个虚拟的例子。我想自动:
-
Resize
BlueItem
's width when I click and dragRedItem
.当我单击并拖动RedItem时,调整BlueItem的宽度。
-
Move
RedItem
when I click and dragBlueItem
.当我单击和拖动BlueItem时,移动RedItem。
The dummy code:
伪代码:
redItem.h (A pixmap item)
redItem。h(象素映射项)
#include <QGraphicsPixmapItem>
class RedItem : public QGraphicsPixmapItem
{
public:
RedItem();
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
};
redItem.cpp
redItem.cpp
RedItem::RedItem()
{
setPixmap(QPixmap(redPixMap));
setFlags(ItemIsMovable);
setCacheMode(DeviceCoordinateCache);
}
void RedItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
setPos(event->scenePos(),0); //I can override this part just fine.
}
blueItem.h (A resizable rectangle item)
blueItem。h(可调整矩形项)
#include <QGraphicsRectItem>
class BlueItem : public QGraphicsRectItem
{
public:
BlueItem();
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
};
blueItem.cpp is similar to redItem.cpp
blueItem。cpp与redItem.cpp相似。
graphicsViewWidget.h (The GraphicsView)
graphicsViewWidget。h(GraphicsView)
#include <QGraphicsView>
#include "blueItem.h"
#include "redItem.h"
class GraphicsViewWidget : public QGraphicsView
{
Q_OBJECT
public:
explicit GraphicsViewWidget(QWidget *parent = 0);
protected:
virtual void mouseMoveEvent(QMouseEvent *event);
private:
RedItem *red;
BlueItem *blue;
};
graphicsViewWidget.cpp
graphicsViewWidget.cpp
#include "graphicsViewWidget.h"
#include <QRectF>
void Qx::createItem(int frame)
{
red = new RedItem;
red->setPos(0, 0);
scene()->addItem(red);
blue = new BlueItem;
blue->setPos(10, 10);
scene()->addItem(blue);
}
void GraphicsViewWidget::mouseMoveEvent(QMouseEvent *event) //QGraphicsSceneMouseEvent
{
QGraphicsView::mouseMoveEvent(event);
//if(redItem moves)
// resize blueItem;
//if(blueItem moves)
// move redItem;
}
Any help or advice would be greatly appreciated.
如有任何帮助或建议,将不胜感激。
1 个解决方案
#1
3
If you make item B a child of item A, then it will live in its coordinate space. This means all transformations - moving, scaling, rotating... everything you apply to the parent item will also be applied to all its children and their children and so on...
如果你让B项成为a项的子元素,那么它就会在它的坐标空间中存在。这意味着所有的转换——移动、缩放、旋转……你向父项目申请的所有东西也将适用于所有的孩子和他们的孩子等等。
#1
3
If you make item B a child of item A, then it will live in its coordinate space. This means all transformations - moving, scaling, rotating... everything you apply to the parent item will also be applied to all its children and their children and so on...
如果你让B项成为a项的子元素,那么它就会在它的坐标空间中存在。这意味着所有的转换——移动、缩放、旋转……你向父项目申请的所有东西也将适用于所有的孩子和他们的孩子等等。