//支持从左到右、从右到左以及左右一直滚动
//textmove.h
#ifndef TEXTMOVE_H
#define TEXTMOVE_H
#include <QWidget>
#include <QTimer>
#include <QFont>
#include <QPainter>
#include <QPaintEvent>
#include <QFontMetrics>
#include <QDebug>
class TextMove : public QWidget
{
Q_OBJECT
public:
enum MoveWay
{
LeftToRight,
RightToLeft,
LeftAndRight
};
explicit TextMove(QWidget *parent = nullptr);
void setText(QString data);
void paintEvent(QPaintEvent *event) override;
void setMoveWay(MoveWay way);
bool toLeft = true;
QFont font;
QTimer *timer;
int x = 0;
int y = 0;
int step = 10;
QString text = "中csgvtrhthergrgth!!";
MoveWay moveWay = RightToLeft;
public slots:
void updateText();
signals:
};
#endif // TEXTMOVE_H
//textmove.cpp
#include "textmove.h"
TextMove::TextMove(QWidget *parent) : QWidget(parent)
{
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &TextMove::updateText);
timer->start(100);
font.setPixelSize(30);
}
void TextMove::setText(QString data)
{
text = data;
}
void TextMove::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QFontMetrics fm(font);
int m_width = fm.width(text);
int m_height = fm.height();
painter.setFont(font);/*
if(width() > m_width)
{
painter.drawText((width()-m_width)/2, (height()-m_height)/2, text);
}
else*/
{
y = (height()-m_height) / 2;
painter.drawText(x, y, text);
if(moveWay == LeftToRight)
{
x += step;
if(x > width())
x = -m_width;
}
else if(moveWay == RightToLeft)
{
x -= step;
if(x < -m_width)
x = width();
}
else if(moveWay == LeftAndRight)
{
if(toLeft)
{
x -= step;
if(x < -m_width)
{
//x = width();
toLeft = false;
}
}
else
{
x += step;
if(x > width())
toLeft = true;
}
}
}
}
void TextMove::setMoveWay(TextMove::MoveWay way)
{
moveWay = way;
}
void TextMove::updateText()
{
update();
}
//widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QMainWindow>
namespace Ui {
class Widget;
}
class Widget : public QMainWindow
{
Q_OBJECT
public:
explicit Widget(QMainWindow *parent = 0);
~Widget();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
//widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QFormLayout>
#include <QLineEdit>
#include <QColumnView>
#include <QStandardItemModel>
#include <QToolBox>
#include <QPushButton>
#include <QTextEdit>
#include <QDockWidget>
#include "textmove.h"
Widget::Widget(QMainWindow *parent) :
QMainWindow(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setFixedSize(800, 480);
setWindowTitle("文字滚动");
TextMove *textMove = new TextMove(this);
textMove->setGeometry(0, 0, 800, 100);
TextMove *textMove1 = new TextMove(this);
textMove1->setGeometry(0, 100, 800, 100);
textMove1->setText("15516nhijnijmoiedvfrvrfeghtfgbhtg");
textMove1->setMoveWay(TextMove::LeftToRight);
TextMove *textMove2 = new TextMove(this);
textMove2->setGeometry(0, 200, 800, 100);
textMove2->setText("I L145614514jiojiojjojoopkcod!rgtrtercsdvdfvbbhbyhnrgv");
textMove2->setMoveWay(TextMove::LeftAndRight);
}
Widget::~Widget()
{
delete ui;
}
11-28
1490
12-09
2957
02-10
1654