实例化一个QPainter类的窗体对象。首先设置该窗体显示的最初透明度为255,即不透明;启动定时器后,以一定的周期重画该窗体并使窗体的透明度递减,直至透明度为0,停止定时器,关闭窗体。
fadewidget.h
#ifndef FADEWIDGET_H #define FADEWIDGET_H #include <QWidget> class QColor; class QTimer; class FaderWidget : public QWidget { Q_OBJECT public: FaderWidget(QWidget *parent); void start(); protected: void paintEvent(QPaintEvent *event); private: QColor startColor; int currentAlpha; int fadeTimes; QTimer *timer; }; #endif // FADER_H
fadewidget.cpp
#include "fadewidget.h" #include <QtGui> FaderWidget::FaderWidget(QWidget *parent) : QWidget(parent) { if (parent) startColor = parent->palette().window().color(); else startColor = Qt::white; currentAlpha = 0; fadeTimes = 1000; timer = new QTimer(this); connect(timer, SIGNAL(timeout()),this, SLOT(update())); setAttribute(Qt::WA_DeleteOnClose); resize(parent->size()); } void FaderWidget::start() { currentAlpha = 255; timer->start(100); show(); } void FaderWidget::paintEvent(QPaintEvent * /* event */) { QPainter painter(this); QColor currentColor = startColor; currentColor.setAlpha(currentAlpha); painter.fillRect(rect(), currentColor); currentAlpha -= 255 * timer->interval() / fadeTimes; if (currentAlpha <= 0) { timer->stop(); close(); } }