1

我正在编写一个基本的可移动 Qt 项目。但有时在移动或按下它时会跳到场景矩形之外。我正在开发 OpenSuse 12.2 + Qt 4.8.1。代码真的很简单。但我找不到问题。

这是我的代码:

TrackLabelItem::PpiTrackLabelItem(PpiTrackItem *pParent, QGraphicsScene *pScene, QGraphicsLineItem *pCombLine)
    : QGraphicsItem(0, pScene), mpParent(pParent), mpCombineLine(pCombLine), mBoundingRect(QRectF(0, 0, 45, 15))
{

    setZValue(TRACK_Z_VALUE);   
    setFlags( ItemIsMovable | ItemSendsGeometryChanges | ItemIgnoresTransformations);
    setCacheMode(QGraphicsItem::DeviceCoordinateCache);
}

TrackLabelItem::~TrackLabelItem()
{

}

QRectF TrackLabelItem::boundingRect() const
{
    return mBoundingRect;
}

void TrackLabelItem::paint(QPainter *pPainter, const QStyleOptionGraphicsItem *pOption, QWidget *pWidget)
{

    pPainter->setRenderHint(QPainter::Antialiasing);
    pPainter->setPen(QPen(Qt::white, /*0.3*/1, Qt::DotLine, Qt::RoundCap, Qt::RoundJoin));
    pPainter->drawRect(mBoundingRect);
    pPainter->setFont(MAP_FONT);
    pPainter->setPen(QPen(Qt::white));
    pPainter->drawText(2, 1, mBoundingRect.width()-2, mBoundingRect.height()-1, Qt::AlignHCenter | Qt::AlignVCenter, mText);

}//paint

void TrackLabelItem::mouseMoveEvent(QGraphicsSceneMouseEvent * pEvent)
{
    update();
    QGraphicsItem::mouseMoveEvent(pEvent);
}

QVariant TrackLabelItem::itemChange(GraphicsItemChange pChange, const QVariant &pValue)
{
    if (pChange == ItemPositionChange && scene())
    {
        // value is the new position.
        QPointF newPos = pValue.toPointF();
        QRectF rect = scene()->sceneRect();
        if (!rect.contains(newPos))
        {
            double rectBottom = rect.bottom() + MAP_SCENE_DIFF;
            // Keep the item inside the scene rect.
            double posX = qMin(rect.right(), qMax(newPos.x(), rect.left()));
            double posY = qMin(rectBottom, qMax(newPos.y(), rect.top()));
            newPos = QPointF(posX, posY);

            return newPos;
        }
    }
    else if(pChange == ItemPositionHasChanged)
    {
        QPointF endPoint(pValue.toPointF().x(), pValue.toPointF().y());
        QPointF startPoint = mpParent->pos();
        mpCombineLine->setLine(QLineF(startPoint, endPoint));

        return QPointF(pValue.toPointF().x(), pValue.toPointF().y());
    }

    return QGraphicsItem::itemChange(pChange, pValue);
}//itemChange
4

0 回答 0