QT QGraphicsItemAnimation

QT QGraphicsItemAnimation

本文关键字:QGraphicsItemAnimation QT      更新时间:2023-10-16
  • 我有一个类:mySquare,它继承自QGraphicsRectItem
  • 只添加了我的构造函数、画家和动画:

动画:

void mySquare::animation(mySquare *k)
{
    QTimeLine *timeLine = new QTimeLine();
    timeLine->setLoopCount(1);
    QGraphicsItemAnimation *animation = new QGraphicsItemAnimation();
    animation->setItem(k);
    animation->setTimeLine(timeLine);
    int value = 30;
    animation->setTranslationAt(0.3, value, value);
    timeLine->start();
// (*)
//        x += 30;  
//        y += 30;
}

画家:

void Klocek::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *widget)
{
bokKwadratu = (min(widget->width(), widget->height()))/5;
setRect(x * 30, y * 30, 30 - 3, 30 - 3);
QRectF rect = boundingRect();
painter->setBrush(brush);
painter->setPen(pen);
QFont font;
font.setPixelSize(bokKwadratu/3);
painter->setFont(font);
painter->drawRect(rect);
painter->drawText(rect,Qt::AlignCenter, QString::number(wartosc));
}

构造函数:

mySquare::mySquare(qreal x, qreal y) : QGraphicsRectItem(x * 10, y * 10, 10, 10)
{
    setAcceptHoverEvents(true);
    this->x = x;
    this->y = y;
    pen.setColor(Qt::red);
    pen.setWidth(2);
    brush.setColor(Qt::blue);
    brush.setStyle(Qt::SolidPattern);
}
  • 在执行动画(翻译(后,我需要更改对象坐标,使其与屏幕上的情况兼容。换句话说,在平移(30,30(之后,我希望矩形的坐标改变(x+=30,y+=30(
  • 我的问题是,当我尝试做这个(代码中的(*(片段(时,三角形被放在离它的位置很远的地方(就像翻译被执行了两次一样(

我的问题是如何在不复杂的情况下翻译和更改坐标。

首先,我认为您误解了函数setTranslationAt在QGraphicsItem Animation中的使用。

动画具有随时间变化的归一化值,因此可以从0.0开始,到1.0结束(或相反(。因此,通过调用

animation->setTranslationAt(0.3, value, value);

您已经说过,当归一化值达到0.3时,您希望将x和y位置设置为"value"。这很好,但你也需要为动画设置其他值(尤其是在1.0的值!(。如果你使用for循环,你可以迭代0.0到1.0的值,并设置你想要的项目位置。看看QGraphicsItemAnimation的Qt帮助文件中的示例代码。QGraphicsItemAnimation使用插值来计算对象在已知点之间的位置。如果你感兴趣:-

http://en.wikipedia.org/wiki/Linear_interpolation

其次,项的rect是项在其局部坐标空间中的定义。因此,如果你想要一个轴在中心的矩形,你可以用(-w/2,-h/2,w,h(的x,y,w来定义它。由于这些是局部坐标,因此它们会被映射到GraphicsScene中的世界坐标中,也就是您在世界中设置其实际位置的地方。

一旦设置了QGraphicsItemRect的局部坐标和世界位置,就可以简单地用drawRect绘制它,而不应该在绘制函数中设置位置。

相关文章:
  • 没有找到相关文章