问题
I'm new to Qt and I'm having some problem with QWidget
rotation.
I have a QPixmap inside a QLabel. What I want is to animate it with a continuous rotation by 90 degrees.
I know QPropertyAnimation
and I know how to use it, but I'm struggling with How to use it for rotating a QWidget
. Is there any simple way to use achieve my goal and rotate the entire QLabel
or the QPixmap
inside it with an animation?
Thank you.
回答1:
This is the demo for rotation of QLabel/QPixmap
with animation.
it's not necessary to use QPropertyAnimation
. Because there is no rotate property for QLabel
or QPixmap
. So used QVariantAnimation
make QPixmap
rotate as animation and use QPixmap::transformed to rotate it. If you want well to control the animation of the pixmap, highly recommend QGraphicsPixmapItem with QPropertyAnimation
class RotateMe : public QLabel {
Q_OBJECT
public:
explicit RotateMe(QWidget* parent = Q_NULLPTR) :
QLabel(parent),
pixmap(100, 100),
animation(new QVariantAnimation )
{
resize(200, 200);
pixmap.fill(Qt::red);
animation->setDuration(10000);
animation->setStartValue(0.0f);
animation->setEndValue(90.0f);
connect(animation, &QVariantAnimation::valueChanged, [=](const QVariant &value){
qDebug()<<value;
QTransform t;
t.rotate(value.toReal());
setPixmap(pixmap.transformed(t));
});
animation->start();
}
private:
QPixmap pixmap;
QVariantAnimation *animation;
};
回答2:
You can implement the rotation in two ways:
1) Create a collection of static images each of which represents the original pixmap rotated by some angle. With a timer you can change your label's pixmap with one from your collection. This will imitate the animated rotation.
2) Use a single pixmap and override your label's QLabel::painEvent()
where you should rotate the QPainter
object with QPainter::rotate()
function each time you redraw the label.
来源:https://stackoverflow.com/questions/50286919/qpropertyanimation-for-rotating-qwidget