Qt实现滚动字幕效果

4 篇文章 0 订阅

http://blog.sina.com.cn/s/blog_75deeddd0100tu2n.html

文字滚动效果
.h文件
#ifndef ROLLCAPTION_H
#define ROLLCAPTION_H
#include <QWidget>
class RollCaption : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(QString text READ text WRITE setText)
public:
    explicit RollCaption(QWidget *parent = 0);
    void setText(const QString &newText);
    QString text() const
    {
        return myText;
    }
    QSize sizeHint() const;
    void setSpeed(const int timer = 50);
    void setcolor(QColor);
protected:
    void paintEvent(QPaintEvent *event);
    void timerEvent(QTimerEvent *event);
    void showEvent(QShowEvent *event);
    void hideEvent(QHideEvent *event);
private:
    QString myText;
    int offset;
    int myTimerId;
    int myTimer;
    QPalette palette;
};
#endif // ROLLCAPTION_H


.cpp文件
#include "rollcaption.h"

#include <QPainter>
#include <qcoreevent.h>
RollCaption::RollCaption(QWidget *parent) :
    QWidget(parent)
{
    this->offset = 0;
    this->myTimerId = 0;
    this->myTimer = 50;
}
void RollCaption::setText(const QString &newText)
{
    this->myText = newText;
    this->update();
    this->updateGeometry();
}
QSize RollCaption::sizeHint() const
{
    return this->fontMetrics().size(0,text());
}
void RollCaption::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QFont wordFont = this->font();
    wordFont.setBold(false);
    wordFont.setPixelSize(24);
    wordFont.setFamily(QString::fromUtf8("\345\276\256\350\275\257\351\233\205\351\273\221"));
    this->setFont(wordFont);
    int textWidth = fontMetrics().width(this->text());
    if(textWidth < 1)
    {
        return;
    }
    int x= -this->offset;
    while(x < width())
    {
        painter.drawText(x,0,textWidth,height(),
                         Qt::AlignLeft  | Qt::AlignVCenter,text());
        x += textWidth;
    }
}
void RollCaption::showEvent(QShowEvent *)
{
    this->myTimerId = startTimer(this->myTimer);
}
void RollCaption::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == this->myTimerId)
    {
        ++this->offset;
        if (this->offset >= this->fontMetrics().width(this->text())) {
            this->offset = 0;
        }
        this->scroll(-1, 0);
    }else
    {
        QWidget::timerEvent(event);
    }
}
void RollCaption::hideEvent(QHideEvent * )
{
    killTimer(myTimerId);
    this->myTimerId = 0;
}
void RollCaption::setSpeed(int timer)
{
    this->myTimer = timer;
}
void RollCaption::setcolor(QColor color)
{
    palette.setColor(QPalette::WindowText,color);
    setPalette(palette);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值