musicamante
说:
覆盖[QGraphicsItem::]
shape
.
以下是如何使
QGraphicsPixmapItem
仅当点击其时可移动
pixmap
,并拥有
boundingRect
围绕它:
class DrawImage : public QGraphicsItem
{
public:
DrawImage()
{
setFlag(ItemIsMovable);
}
protected:
QRectF boundingRect() const override
{
return QRectF(0, 0, 100, 200);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
auto greenBall = QPixmap(":green.svg");
QRect rect = boundingRect().toRect();
//You can adjust where your pixmap is drawn
//I chose the upper part of the bounding rect
rect.adjust(0,0,0,-rect.height()/2);
painter->drawPixmap(rect, greenBall);
//I'm drawing the full bounding rect just to make it visible
painter->setPen(Qt::green);
painter->drawRect(boundingRect());
}
QPainterPath shape() const
{
//this is where you sepecify which area of your object allows the user to move it when clicked
auto greenBall = QPixmap(":green.svg");
QRect rect = boundingRect().toRect();
//Make sure it is the same area where you're drawing your pixmap
rect.adjust(0,0,0,-rect.height()/2);
QPainterPath path;
//add it as the shape you want, I chose an ellipse for the green circle
path.addEllipse(rect);
return path;
}
};
结果如下:
有关更多详细信息,请参阅源代码: