在学习《Foundations of Qt Development》中的7-20. A shape containing two other shapes + 7.21 Transforming the five items 时涉及到这些图形操作:translate 平移,scale 缩放,rotate 顺时针转动,shear 扭曲
我的环境是:Qt Creator 2.8.1;Based on Qt 5.1.1 (GCC 4.6.1, 32 bit)
编码时发现QGraphicsItem没有translate、shear。
在帮助中搜索找到了另一个类:QGraphicsItemAnimation
它提供了许多有用的函数,其中就包括了
void QGraphicsItemAnimation::setTranslationAt(qreal step, qreal dx, qreal dy);
void QGraphicsItemAnimation::setShearAt(qreal step, qreal sh, qreal sv);
设定step的初值,调用图形变化函数,最后改变step value,使得变化函数发挥作用。需要注意的是step value数值范围在[0,1]。
#include <QApplication>
#include <QtWidgets>
QGraphicsItem *createItem(int x){
/* QRectF(qreal x, qreal y, qreal width, qreal height) */
QGraphicsRectItem *rect = new QGraphicsRectItem(QRectF(QPointF(x,0),QPointF(x+100,100)));
rect->setPen(QPen(Qt::red));
rect->setBrush(QBrush(Qt::gray,Qt::SolidPattern));
QGraphicsRectItem *innerRect = new QGraphicsRectItem\
(QRectF(QPointF(x+10,10),QPointF(x+40,90)),rect);
innerRect->setPen(QPen(Qt::green));
innerRect->setBrush(QBrush(Qt::blue,Qt::Dense3Pattern));
QGraphicsEllipseItem *ellipse = new QGraphicsEllipseItem(\
QRectF(QPointF(x+60,10),QPointF(x+90,90)),rect);
ellipse->setPen(QPen(Qt::yellow));
ellipse->setBrush(QBrush(Qt::darkCyan,Qt::Dense7Pattern));
return rect;
}
int main(int argc,char **argv){
QApplication app(argc,argv);
QGraphicsScene *scene = new QGraphicsScene(QRectF(-10,-10,550,450));
QGraphicsItem *item1 = createItem(0);
item1->setRotation(30);
scene->addItem(item1);
QGraphicsItem *item2 = createItem(110);
item2->setScale(0.5);
scene->addItem(item2);
QGraphicsItem *item3 = createItem(220);
/* You can schedule changes to the item's transformation matrix at specified steps.
*The QGraphicsItemAnimation class has a current step value. When this value changes
*the transformations scheduled at that step are performed. The current step of the
*animation is set with the setStep() function. ... Note that steps lie between 0.0 and 1.0. */
/* void QGraphicsItemAnimation::setTranslationAt(qreal step, qreal dx, qreal dy)
* Sets the translation of the item at the given step value using the horizontal
*and vertical coordinates specified by dx and dy. */
QGraphicsItemAnimation *animation = new QGraphicsItemAnimation();
animation->setItem(item3);
animation->setStep(0);
animation->setTranslationAt(0,0,50);
animation->setStep(0.2);
scene->addItem(item3);
QGraphicsItem *item4 = createItem(330);
animation->setItem(item4);
animation->setShearAt(0.2,0.5,0.5);
animation->setStep(0.3);
scene->addItem(item4);
QGraphicsView view;
view.setScene(scene);
view.show();
return app.exec();
}