QWidget::paintEvent 被调用的场景

一般情况下,若通过Qt实现绘图,需要重写此函数。

Qt助手给出如下解释:

void QWidget::paintEvent ( QPaintEvent * event ) [virtual protected]
This event handler can be reimplemented in a subclass to receive paint events passed in event.


A paint event is a request to repaint all or part of a widget. It can happen for one of the following reasons:


1) repaint() or update() was invoked,   (此时可通过定时器关联update槽,间接实现对paintEvent 函数的调用)

   例子如下:


class OvenTimer : public QWidget
{
    Q_OBJECT
 
  
public:
    OvenTimer(QWidget *parent = 0);
 
  
    void setDuration(int secs);
    int duration() const;
    void draw(QPainter *painter);
 
  
signals:
    void timeout();
 
  
protected:
    void paintEvent(QPaintEvent *event);
    void mousePressEvent(QMouseEvent *event);
 
  
private:
    QDateTime finishTime;
    QTimer *updateTimer;
    QTimer *finishTimer;
};

    .cpp 

OvenTimer::OvenTimer(QWidget *parent)
    : QWidget(parent)
{
    finishTime = QDateTime::currentDateTime();
 
  
    updateTimer = new QTimer(this);
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(update()));


通过上面的信号槽关系,即间接的调用了paintEvent 函数。因此只需要实现paintEvent 函数即可。


2) the widget was obscured and has now been uncovered, or (重新实现一个widget时也会导致对对paintEvent 函数的调用)

     例子如下:

        

class MyWidget : public QWidget
{
  Q_OBJECT
 
  
public:
    MyWidget(QWidget *parent=0);
    ~MyWidget();
 
  
    void paintEvent(QPaintEvent *event);
};

只需要重新实现paintEvent即可。


3)many other reasons.

你可能感兴趣的:(QT)