I'm newbie to Qt. Now I'm learning about Scrolling the Text in a QWidget. When my text size is lesser than the Widget then the text should scroll only once till it reaches the end (text is moved from right to left). once it reaches the left end then again it should start from the right end. plz help me to do this... Thanks in advance..
*Here is my Coding....*
**ScrollText.h**
#ifndef SCROLLTEXT_H
#define SCROLLTEXT_H
#include <QWidget>
#include <QStaticText>
#include <QTimer>
class ScrollText : public QWidget
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText)
Q_PROPERTY(QString separator READ separator WRITE setSeparator)
public:
explicit ScrollText(QWidget *parent = 0);
public slots:
QString text() const;
void setText(QString text);
QString separator() const;
void setSeparator(QString separator);
protected:
void paintEvent(QPaintEvent *);
private:
void updateText();
QString _text;
QString _separator;
QStaticText staticText;
int singleTextWidth;
QSize wholeTextSize;
int leftMargin;
int scrollPos;
QImage buffer;
QTimer timer;
private slots:
virtual void timer_timeout();
};
#endif // SCROLLTEXT_H
**ScrollText.cpp**
#include "Widget.h"
#include <QPainter>
#include <QDebug>
ScrollText::ScrollText(QWidget *parent) :
QWidget(parent), scrollPos(0)
{
staticText.setTextFormat(Qt::PlainText);
setFixedHeight(fontMetrics().height());
leftMargin = width();
setSeparator(" ");
connect(&timer, SIGNAL(timeout()), this, SLOT(timer_timeout()));
timer.setInterval(30);
}
QString ScrollText::text() const
{
return _text;
}
void ScrollText::setText(QString text)
{
_text = text;
updateText();
update();
}
QString ScrollText::separator() const
{
return _separator;
}
void ScrollText::setSeparator(QString separator)
{
_separator = separator;
updateText();
update();
}
void ScrollText::updateText()
{
singleTextWidth = fontMetrics().width(_text);
timer.start();
scrollPos = 0;
staticText.setText(_text + _separator);
staticText.prepare(QTransform(), font());
wholeTextSize = QSize(fontMetrics().width(staticText.text()), fontMetrics().height());
timer.stop();
}
void ScrollText::paintEvent(QPaintEvent*)
{
QPainter painter(this);
buffer = QImage(size(), QImage::Format_ARGB32_Premultiplied);
buffer.fill(qRgba(0, 0 ,0, 0));
QPainter pb(&buffer);
pb.setPen(painter.pen());
pb.setFont(painter.font());
int x = qMin(-scrollPos, 0)+ leftMargin + (leftMargin/2);
if(x < width())
{
pb.drawStaticText(QPointF(x, (height() - wholeTextSize.height()) / 2) + QPoint(0,0), staticText);
x += wholeTextSize.width();
if(x < 0)
{
scrollPos = 0;
}
painter.drawImage(0, 0, buffer);
}
}
void ScrollText::timer_timeout()
{
scrollPos = (scrollPos+ 2);
update();
}