温馨提示×

Qt实现字幕滚动效果的示例代码

qt
小云
141
2023-08-11 14:11:16
栏目: 编程语言

以下是一个使用Qt实现字幕滚动效果的示例代码:

#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QTimer>
#include <QPropertyAnimation>
class ScrollLabel : public QLabel
{
Q_OBJECT
Q_PROPERTY(int scrollPos READ scrollPos WRITE setScrollPos)
public:
ScrollLabel(QWidget* parent = nullptr) : QLabel(parent), m_scrollPos(0)
{
setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
setWordWrap(false);
}
int scrollPos() const { return m_scrollPos; }
void setScrollPos(int pos) { m_scrollPos = pos; update(); }
protected:
void paintEvent(QPaintEvent* event) override
{
QPainter painter(this);
painter.setClipRect(event->rect());
// 绘制文本
QString text = this->text();
int textWidth = fontMetrics().width(text);
int offset = -m_scrollPos;
while (offset < width()) {
painter.drawText(offset, 0, textWidth, height(), Qt::AlignLeft, text);
offset += textWidth;
}
}
private:
int m_scrollPos;
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QWidget widget;
widget.resize(400, 100);
ScrollLabel label(&widget);
label.setGeometry(0, 0, 400, 100);
label.setText("This is a scrolling subtitle.");
// 创建动画对象
QPropertyAnimation animation(&label, "scrollPos");
animation.setDuration(5000); // 动画持续时间(毫秒)
animation.setStartValue(0);
animation.setEndValue(label.fontMetrics().width(label.text())); // 文本宽度
animation.setLoopCount(-1); // 无限循环播放
// 定时器触发动画开始
QTimer::singleShot(1000, [&animation]() {
animation.start();
});
widget.show();
return app.exec();
}
#include "main.moc"

这个示例中,我们定义了一个名为ScrollLabel的自定义QWidget,它继承自QLabel。在ScrollLabel中,我们通过重写paintEvent函数来实现滚动效果。我们使用QPropertyAnimation来控制滚动位置的动画。在主函数中,我们创建了一个ScrollLabel实例,并设置了需要滚动的文本。然后使用定时器触发动画开始。运行程序后,你将看到字幕以滚动的方式在窗口中显示。

0