关闭

Qt 水平滚动字幕2

545人阅读 评论(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
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5076次
    • 积分:68
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:5篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档