user2653112
user2653112

Reputation: 31

Qlabel and Qtimer (need to make image blink)

I have got two Q labels with images on them, which I need to blink every few seconds.

I don't understand how I could implement it with a QLabel.

Screenshot of what I have now:

Screenshot with the example

Upvotes: 3

Views: 5988

Answers (2)

Cameron Tinker
Cameron Tinker

Reputation: 9789

I've adapted the example code you linked to for QLabel:

#include <QtGui>

class BlinkLabel : public QLabel
{
  Q_OBJECT
  public :
  BlinkLabel(QPixmap * image1, QPixmap * image2)
  {
    m_image1 = image1;
    m_image2 = image2;
    m_pTickTimer = new QTimer();    
    m_pTickTimer->start(500);

    connect(m_pTickTimer,SIGNAL(timeout()),this,SLOT(tick()));
  };
  ~BlinkLabel()
  {
    delete m_pTickTimer;
    delete m_image1;
    delete m_image2;       
  };

  private slots:
    void tick()
    {
      if(index%2)
      {
        setPixMap(*m_image1);
        index--;
      }
      else
      {
        setPixMap(*m_image2);
        index++;
      }      
    };    
  private:
    QTimer* m_pTickTimer;
    int index;
    QPixmap* m_image1;
    QPixmap* m_image2;
};

Then all you'd need to do is create an instance of BlinkLabel like this:

QPixmap* image1 = new QPixmap(":/image1.png");
QPixmap* image2 = new QPixmap(":/image2.png");
BlinkLabel blinkLabel = new BlinkLabel(image1, image2); // alternates between image1 and image2 every 500 ms

Upvotes: 1

Sylvain V
Sylvain V

Reputation: 194

Create a QTimer, connect the timeout() signal to a slot, and in the slot you can do whatever you want to your QLabel !

myclass.h:

class MyClass : public QWidget
{
    Q_OBJECT
public:
    explicit MyClass(QWidget *parent = 0);

public slots:
    void timeout();

private:
    QTimer  *timer;
    QLabel  *label;

    int     counter;
};

myclass.cpp:

#include "myclass.h"

MyClass::MyClass(QWidget *parent) :
    QWidget(parent)
{
    timer = new QTimer();

    label = new QLabel();

    counter = 0;

    connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));

    timer->start(1000);
}

void MyClass::timeout()
{
    if(counter%2)
        label->setText("Hello !");
    else
        label->setText("Good bye...");
    counter++;
}

Upvotes: 3

Related Questions