实现一个标签内的字从右向左滚动。新建一个widget窗体,在上面放一个标签。

widget.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>Widget</string>
</property>
<widget class="QLabel" name="label">
<property name="geometry">
<rect>
<x>210</x>
<y>220</y>
<width>331</width>
<height>211</height>
</rect>
</property>
<property name="font">
<font>
<pointsize>12</pointsize>
<bold>true</bold>
</font>
</property>
<property name="frameShape">
<enum>QFrame::Shape::Box</enum>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void setText(const QString &newText);
private:
Ui::Widget *ui;
int myTimerId;
QString str; //存储显示字符串
QString tempStr;
protected:
void timerEvent(QTimerEvent *event);
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setFocus();
myTimerId=startTimer(300);
}
Widget::~Widget()
{
delete ui;
}
void Widget::setText(const QString &newText)
{
str=newText;
tempStr=str.leftJustified(str.length()*2-1,' ');
}
void Widget::timerEvent(QTimerEvent *event)
{
if(event->timerId()==myTimerId)
{
tempStr=tempStr.mid(1)+tempStr.left(1);
ui->label->setText(tempStr.mid(0,str.length()));
this->update();
}
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.setText(QObject::tr("Winter is coming"));//要显示的字符串
w.show();
return a.exec();
}
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
widget.cpp
HEADERS += \
widget.h
FORMS += \
widget.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
