QLabel和QTimer(需要使图像闪烁)

3
我有两个带图像的Q标签,需要每隔几秒钟闪烁一次。但我不知道如何使用QLabel实现它。
现在是示例截图:Screenshot with the example

1
你提供的代码非常简单。你不理解什么?你需要创建一个QTimer,并将超时槽连接到交替QLabel显示(闪烁)的信号。 - Cameron Tinker
2个回答

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++;
}

是的,我不太明白你想要用标签做什么,但如果你想要隐藏/显示它们,你可以使用label->hide();和label->show();。setText()只是一个例子。 - Sylvain V

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

嗨,感谢您的回答,您能看一下我的编辑吗?这些是我的源文件,并附有我的UI截图,请问我需要在源文件中放置什么才能将其链接到“label”和“label_2”?再次感谢! - user2653112
我已经更新了我的答案,以反映如何在QLabel上交替显示图像。 - Cameron Tinker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接