Qt 水平滚动字幕2

4 篇文章 0 订阅

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

// widget.h"

#ifndef WIDGET_H

#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(QString text READ text WRITE setText)
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
    void setText(const QString &newText);
        QString text() const { return myText; }
        QSize sizeHint() const;
protected:
     void paintEvent(QPaintEvent *event);
     void timerEvent(QTimerEvent *event);
     void showEvent(QShowEvent *event);
     void hideEvent(QHideEvent *event);
private:
     QString myText;
     int offset;
     int myTimerId;
private:
    Ui::Widget *ui;
};
#endif // WIDGET_H
 
// widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <qcoreevent.h>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    offset = 0;
         myTimerId = 0;
}
Widget::~Widget()
{
    delete ui;
}
void Widget::setText(const QString &newText)
{
     myText = newText;
     update();
     updateGeometry();
}
QSize Widget::sizeHint() const
{
     return fontMetrics().size(0, text());
}
void Widget::paintEvent(QPaintEvent * )
{
     QPainter painter(this);
     int textWidth = fontMetrics().width(text());
     if (textWidth < 1)
         return;
     int x = -offset;
     while (x < width()) {
         painter.drawText(x, 0, textWidth, height(),
                         Qt::AlignLeft | Qt::AlignVCenter, text());
         x += textWidth;
     }
}
void Widget::showEvent(QShowEvent * )
{
     myTimerId = startTimer(30);
}
void Widget::timerEvent(QTimerEvent *event)
{
     if (event->timerId() == myTimerId) {
         ++offset;
         if (offset >= fontMetrics().width(text()))
             offset = 0;
         scroll(-1, 0);
     } else {
         QWidget::timerEvent(event);
     }
}
void Widget::hideEvent(QHideEvent * )
{
     killTimer(myTimerId);
     myTimerId = 0;
}
 
// main.cp
#include <QtGui/QApplication>
#include "widget.h"
#include <QLabel>
#include <QGridLayout>
#include <QTextCodec>
#include <QIcon>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.setWindowTitle(QObject::tr("Ticker"));
        w.setText(QObject::tr("How long it lasted was impossible to "
                                  "say ++ "));
    w.show();
    return a.exec();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值