功能
文字长度小于label时,label上的文字不滚动,当大于label的长度时,实现文字的滚动效果。
效果展示
原理
通过重写QLabel,使用mid、left函数将字符串进行分割,通过append函数使分割后的字符串进行连接,绑定定时器达到滚动的效果。
源码
.h文件
:
#ifndef SCROLL_H
#define SCROLL_H
#include <QObject>
#include<QLabel>
#include<QWidget>
#include <QTimer>
class Scroll : public QLabel
{
Q_OBJECT
public:
Scroll(QWidget *parent = 0);
public:
void showScrollText(QString text);
private:
QTimer m_TimerRoll;
QString showText;
private slots:
void updateIndex();
};
#endif // SCROLL_H
.cpp文件
:
#include "scroll.h"
#define IDLENTH 10
Scroll::Scroll(QWidget *parent):QLabel(parent)
{
connect(&m_TimerRoll, SIGNAL(timeout()), this, SLOT(updateIndex()));
}
void Scroll::showScrollText(QString text)
{
if(m_TimerRoll.isActive())
m_TimerRoll.stop();
showText = text;
m_TimerRoll.start(300);
}
void Scroll::updateIndex()
{
static int nPos = 0;
if(showText != NULL)
{
if (nPos > showText.length())
{
nPos = 0;
}
this->setText(showText.mid(nPos));
QString str = this->text().append(" "+showText.left(nPos));
this->setText(str);
nPos++;
if(showText.length() < IDLENTH)
{
this->setText(showText);
}
}
}
注意
需要将ui上的label提升为已经重写的label类才可正常显示。