您的位置:首页 > 编程语言 > Qt开发

Qt 5滚动字幕(左/右)+闪烁效果(QLabel控件显示)

2017-12-07 15:51 1641 查看

一、说明:

Qt版本为:Qt 5.9.1

二、简单解述:

1、字幕效果主要是应用QString QString::mid(int pos, int n = -1) const函数截取字符,另外需要一个定时器刷新(QTimer),具体信息可以参考Qt帮助文档,索引mid,过滤QString class。

2、闪烁效果很简单,用hide和show函数即可,使用一个定时器刷新。

3、效果展示:



三、上代码:

1、ui部分:

拖动一个label和button到界面中,设置好label的字体颜色和大小,字体颜色可以直接在ui中改变样式表。

2、头文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void scrollCaption();
void show_hide();

void on_twinkleBt_clicked();

private:
Ui::MainWindow *ui;

QTimer *mtimer;
QTimer *ntimer;
QString showtext;
int curIndex;
};

#endif // MAINWINDOW_H


3、.cpp代码:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

//#define RT

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

ui->twinkleBt->setText("关闭闪烁");

#ifndef RT
curIndex = showtext.size(); //左移
#endif
#ifdef RT
curIndex = 0; // 右移
#endif

showtext = "天气变冷,请同学们注意保暖!";
mtimer = new QTimer(this);
connect(mtimer, SIGNAL(timeout()), this, SLOT(scrollCaption()));
mtimer->start(1000);

ntimer = new QTimer(this);
connect(ntimer, SIGNAL(timeout()), this, SLOT(show_hide()));
ntimer->start(250);
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::scrollCaption()
{
int isize = showtext.size(); // 文字个数

4000
#ifndef RT // 左移
if (curIndex > isize)
curIndex = 0;
qDebug() << curIndex;
ui->label->setText(showtext.mid(curIndex++)); // .mid(pos); 从pos开始截取字符串
#endif

#ifdef RT // 右移
if (curIndex < 0)
curIndex = isize;
ui->label->setText(showtext.mid(curIndex--));
#endif
}

void MainWindow::show_hide()
{
if (ui->label->isHidden() == true)
ui->label->show();
else
ui->label->hide();
}

// 停止/开启闪烁
void MainWindow::on_twinkleBt_clicked()
{
if (ntimer->isActive() == true)
{
disconnect(ntimer, SIGNAL(timeout()), this, SLOT(show_hide()));
ntimer->stop();

if (ui->label->isHidden() == true)
ui->label->show();

ui->twinkleBt->setText("开启闪烁");
}
else
{
connect(ntimer, SIGNAL(timeout()), this, SLOT(show_hide()));
ntimer->start(250);

ui->twinkleBt->setText("关闭闪烁");
}
}


工程打包下载:http://download.csdn.net/download/wu9797/10149734
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: