【发布时间】:2015-07-30 18:47:26
【问题描述】:
我正在用 Qt 设计一个计时器。使用 QGraphicsEllipseItem,我画了一个圆圈,现在我需要每秒围绕这个圆圈为 QPen 设置动画(改变颜色)。我找到了 QGraphicsPathItem,但我需要一些关于如何前进的示例。谁能给我举个例子?
【问题讨论】:
标签: qt qgraphicsview qgraphicsitem
我正在用 Qt 设计一个计时器。使用 QGraphicsEllipseItem,我画了一个圆圈,现在我需要每秒围绕这个圆圈为 QPen 设置动画(改变颜色)。我找到了 QGraphicsPathItem,但我需要一些关于如何前进的示例。谁能给我举个例子?
【问题讨论】:
标签: qt qgraphicsview qgraphicsitem
你有两个问题:
QGraphicsEllipseItem 不是QObject 所以QPropertyAnimation 不能直接用在这个项目上QGraphicsItemAnimation 不包括您要设置动画的属性。你能做什么?
IMO 最好的方法是提供一些自定义的QObject,你可以在上面做这个动画。您可以继承QObject 或使用假的QGraphicsObject(即QObject)。
class ShapeItemPenAnimator : public QGraphicsObject {
Q_OBJECT
private:
QAbstractGraphicsShapeItem *mParent;
QPropertyAnimation *mAnimation;
public:
QPROPERTY(QColor penColor
READ penColor
WRITE setPenColor)
explicit ShapeItemPenAnimator(QAbstractGraphicsShapeItem * parent)
: QGraphicsObject(parent)
, mParent(parent) {
setFlags(QGraphicsItem::ItemHasNoContents);
mAnimation = new QPropertyAnimation(this, "penColor", this);
}
QColor penColor() const {
return mParent->pen().color();
}
public slots:
void setPenColor(const QColor &color) {
QPen pen(mParent->pen());
pen.setColor(color);
mParent->setPen(pen);
}
public:
void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0) {
}
QRectF boundingRect() const {
return QRectF();
}
QPropertyAnimation *animation() const {
return mAnimation;
}
}
现在您只需将此对象附加到您的 QGraphicsEllipseItem 并设置您需要的动画。
// yourEllipse
ShapeItemPenAnimator *animator = new ShapeItemPenAnimator(yourEllipse);
animator->animation()->setEndValue(....);
animator->animation()->setStartValue(....);
animator->animation()->setDuration(....);
animator->animation()->setEasingCurve(....);
【讨论】:
boindingRect.
ShapeItemPenAnimator 只是可以公开属性的代理对象,因为它是QObject。它不做任何其他事情。就像我写的那样,您可以继承 QObject 并获得相同的结果,但在这种情况下,内存管理更加困难(这就是我使用 QGraphicsObject 的原因)。关于属性动画阅读其文档。这个setTarget我写错了它不应该在那里(我已经修复了)。
Qt 中有几个类可以帮助处理 QGraphicsItem 的动画。我建议调查QGraphicsItemAnimation 和QPropertyAnimation。您可以使用第二个动画项目的颜色。这是使用 QPropertyAnimation 的示例: How to make Qt widgets fade in or fade out?
【讨论】: