利用QLabel实现一个滚动字幕(跑马灯),同时需要有倒计时功能。
思路:
1、重绘QLabel类,利用定时器在paintEvent()中修改内容的位置,即实现跑马灯功能;
2、主界面中启动定时器实现倒计时,并实时给跑马灯label设置文本。
代码:
1、重绘Qlabel类:
#ifndef MARQUEELABEL_H
#define MARQUEELABEL_H
#include <QObject>
#include <QLabel>
class MarqueeLabel : public QLabel
{
Q_OBJECT
public:
explicit MarqueeLabel(QWidget *parent = nullptr);
void setText(const QString &text);
signals:
protected:
void paintEvent(QPaintEvent *event);
void updateWord();
private:
int m_widthPerword;
int m_curCount;
QString m_text;
};
#endif // MARQUEELABEL_H
#include "marqueelabel.h"
#include <QPainter>
#include <QTimer>
MarqueeLabel::MarqueeLabel(QWidget *parent) : QLabel(parent)
{
m_curCount = 0;//当前角码
m_widthPerword = fontMetrics().width("a");//每个字符的宽度
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &MarqueeLabel::updateWord);
timer->start(200);
}
void MarqueeLabel::paintEvent(QPaintEvent *event)
{
__super::paintEvent(event);
QPainter painter(this);
painter.drawText(0, 80, m_text.mid(m_curCount));
painter.drawText(width() - m_widthPerword*m_curCount, 80, m_text.left(m_curCount));
}
void MarqueeLabel::updateWord()
{
update();
m_curCount++;
if (m_curCount*m_widthPerword > width())
m_curCount = 0;
}
void MarqueeLabel::setText(const QString &text)
{
m_text = text;
}
2、主界面调用:
#ifndef MARQUEETEST_H
#define MARQUEETEST_H
#include <QWidget>
#include <QLCDNumber>
#include <QPalette>
#include <QTimer>
namespace Ui {
class MarqueeTest;
}
class MarqueeTest : public QWidget
{
Q_OBJECT
public:
explicit MarqueeTest(QWidget *parent = nullptr);
~MarqueeTest();
private:
Ui::MarqueeTest *ui;
// QLCDNumber *numb;
QTimer *timer;
int time = 15000; //15second
private slots:
void function();
void on_closeButton_clicked();
};
#endif // MARQUEETEST_H
#include "marqueetest.h"
#include "ui_marqueetest.h"
MarqueeTest::MarqueeTest(QWidget *parent) :
QWidget(parent),
ui(new Ui::MarqueeTest)
{
ui->setupUi(this);
this->setAttribute(Qt::WA_StyledBackground);
this->setWindowFlag(Qt::FramelessWindowHint);
timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(function()));
timer->start(1000);
}
MarqueeTest::~MarqueeTest()
{
delete ui;
}
void MarqueeTest::function()
{
if(time == 0 || time > 0){
//ui->textLabel提升为MarqueeLabel
ui->textLabel->setText(QStringLiteral("会议还有%1秒开始,请做好准备!").arg(time/1000));
}
else{
ui->textLabel->setText(QStringLiteral("会议已开始,请安静"));
timer->stop();
}
time = time - 1000;
}
void MarqueeTest::on_closeButton_clicked()
{
this->close();
}