Qlabel和Qtimer(需要使图像闪烁)

时间:2013-08-05 12:35:07

标签: qt

![在此处输入图像说明] [1]我有两个带有图像的Q标签,我需要每隔几秒闪烁一次。

我一直在寻找这个例子:http://www.codeprogress.com/cpp/libraries/qt/showQtExample.php?index=357&key=QLCDNumberBlinkingClock

但是,不明白我如何使用QLabel

来实现它

提前致谢。

2 个答案:

答案 0 :(得分:3)

创建一个QTimer,将timeout()信号连接到一个插槽,在插槽中,您可以对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++;
}

答案 1 :(得分:1)

我已经调整了您链接到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;
};

然后你需要做的就是像这样创建一个BlinkLabel实例:

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