[SOLVED] Disable QBrush rotating inside QGraphicsItem.
-
Hi,
I am attempting to draw QGraphicsRectItem object. I would like the brush not to rotate as the QGraphicsRectItem object is rotated.Does anybody know how can I achieve this?
My implementation is below:
graphicsrectitem.h
@class GraphicsRectItem : public QGraphicsRectItem
{
public:
GraphicsRectItem();protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);private:
QPointF _initialPos;
qreal _rotation;
QTransform _transform;
bool _isTransformed;
};@graphicsrectitem.cpp
@GraphicsRectItem::GraphicsRectItem() :
_rotation(0),
_isTransformed(false)
{
setFlag(ItemIsMovable);
setFlag(ItemSendsGeometryChanges);
}void GraphicsRectItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
_initialPos = mapToScene(event->pos());
QGraphicsItem::mousePressEvent(event);
}void GraphicsRectItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QPointF pos = mapToScene(event->pos());if (pos.y() > _initialPos.y()) ++_rotation; else --_rotation; setRotation(_rotation); _initialPos = pos; brush().setTransform(_transform);
}
void GraphicsRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem option, QWidget)
{
QLinearGradient gradient;
gradient.setColorAt(0, Qt::white);
gradient.setColorAt(1, Qt::gray);
QBrush brush(gradient);
painter->setBrush(brush);
painter->drawRect(-40, -30, 80, 60);if (!_isTransformed) { _isTransformed = true; _transform = brush.transform(); }
}
@ -
Get the current object rotation and apply negative rotation to the brush before painting, i.e. change this:
@
QBrush brush(gradient);
painter->setBrush(brush);
@
to
@
QBrush brush(gradient);
QTransform t;
t.rotate(-rotation());
brush.setTransform(t);
painter->setBrush(brush);
@