步骤
- 定义一个继承QLabel的ScrollingLabel类
- 在所需的界面类ui上定义一个button,定义全局变量
- 运用
scrollinglabel.h
#ifndef SCROLLINGLABEL_H
#define SCROLLINGLABEL_H#include <QLabel>
#include <QPushButton>
#include <QLabel>
#include <QTimer>
#include <QPainter>class ScrollingLabel : public QLabel
{
public:explicit ScrollingLabel(QWidget *parent = nullptr);protected:void paintEvent(QPaintEvent *event) override ;private slots:void updateOffset();private:int offset; // 当前滚动的偏移量QTimer *timer; // 定时器控制滚动
};#endif // SCROLLINGLABEL_H
scrollinglabel.cpp
#include "scrollinglabel.h"
#include <QPushButton>
#include <QLabel>
#include <QTimer>
#include <QPainter>ScrollingLabel::ScrollingLabel(QWidget *parent): QLabel(parent), offset(0) {setStyleSheet("color: white; background: transparent;"); // 设置文本为白色,背景透明// 定时器滚动timer = new QTimer(this);connect(timer, &QTimer::timeout, this, &ScrollingLabel::updateOffset);timer->start(100);
}
void ScrollingLabel::paintEvent(QPaintEvent *event){QPainter painter(this);// 设置文本的字体和颜色painter.setPen(Qt::white);painter.setFont(font());// 获取文本的宽度int textWidth = fontMetrics().horizontalAdvance(text());// 判断文本的宽度有没有大于label宽度if (textWidth > width()) {// 偏移位置int x = -offset % textWidth;painter.drawText(x, height() / 2 + fontMetrics().ascent() / 2, text());painter.drawText(x + textWidth, height() / 2 + fontMetrics().ascent() / 2, text());} else {// 如果文本宽度小于控件宽度,则居中绘制painter.drawText(rect(), Qt::AlignCenter, text());}
}
void ScrollingLabel::updateOffset() {offset += 2;update();
}
运用
ScrollingLabel *scrollLabel;scrollLabel = new ScrollingLabel(ui->btn);scrollLabel->setStyleSheet("color: white; background: transparent;"); // 文本白色,背景透明scrollLabel->setAlignment(Qt::AlignCenter);scrollLabel->setText("");scrollLabel->resize(ui->btn->width() - 40 , ui->btn->height());scrollLabel->move(20, 0);scrollLabel->setText(text);