如何使Qt小部件淡入淡出或淡出?

Sou*_*Das 22 animation qt opacity fadeout qpainter

我试图淡入并淡出一个QLabel或任何子QWidget类.我尝试过QGraphicsEffect,但不幸的是它只适用于Windows而不适用于Mac.

唯一可以同时适用于Mac和Windows的其他解决方案似乎是我自己的自定义paintEvent设置不透明度,QPainterQ_PROPERTY在我的派生中定义"不透明度" QLabel并通过改变不透明度QPropertyAnimation.

我粘贴在相关代码段下方供您参考.我仍然在这里看到一个问题 - 重复使用QLabel::paintEvent它似乎不起作用,它只有在我使用它完成一个完整的自定义绘画时才有效QPainter,但这似乎不是一个简单的方法,如果我需要为每个人都这样做QWidget子类我想淡出,这是一场噩梦.请澄清我在这里是否有任何明显的错误.

Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity)

void MyLabel::setOpacity(qreal value) {
    m_Opacity = value;
    repaint();
}

void MyLabel::paintEvent((QPaintEvent *pe) {
    QPainter p;
    p.begin(this);
    p.setOpacity();
    QLabel::paintEvent(pe);
    p.end();
}

void MyLabel::startFadeOutAnimation() {
    QPropertyAnimation *anim = new QPropertyAnimation(this, "opacity");
    anim->setDuration(800);
    anim->setStartValue(1.0);
    anim->setEndValue(0.0);
    anim->setEasingCurve(QEasingCurve::OutQuad);
    anim->start(QAbstractAnimation::DeleteWhenStopped);
}
Run Code Online (Sandbox Code Playgroud)

Vol*_*ike 30

实际上有一种非常简单的方法可以做到这一点而不会有杂乱的QPaintEvent拦截,也没有严格的要求QGraphicsProxyWidget,这对于提升的小部件子项无效.下面的技术甚至可以用于推广的小部件及其子窗口小部件.

淡入你的小工具

// w is your widget
QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
w->setGraphicsEffect(eff);
QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity");
a->setDuration(350);
a->setStartValue(0);
a->setEndValue(1);
a->setEasingCurve(QEasingCurve::InBack);
a->start(QPropertyAnimation::DeleteWhenStopped);
Run Code Online (Sandbox Code Playgroud)

淡出你的小工具

// w is your widget
QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
w->setGraphicsEffect(eff);
QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity");
a->setDuration(350);
a->setStartValue(1);
a->setEndValue(0);
a->setEasingCurve(QEasingCurve::OutBack);
a->start(QPropertyAnimation::DeleteWhenStopped);
connect(a,SIGNAL(finished()),this,SLOT(hideThisWidget()));
// now implement a slot called hideThisWidget() to do
// things like hide any background dimmer, etc.
Run Code Online (Sandbox Code Playgroud)

  • **重要** 如果在 python 中运行这段代码,你需要保存 `a` 和 `eff` 变量(`self.a=`),这样它们就不会被垃圾收集 (4认同)

Pav*_*hov 1

您可以将您的小部件放入QGraphicsScene. 它支持不透明度更改和动画。

请参阅QGraphicsProxyWidget文档中的示例。