我有两个带图像的Q标签,需要每隔几秒钟闪烁一次。但我不知道如何使用QLabel实现它。
现在是示例截图:
现在是示例截图:
![Screenshot with the example](https://istack.dev59.com/kxTQQ.webp)
创建一个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++;
}
我已经根据你提供的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;
};
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