Qt 5滾動字幕(左/右)+閃爍效果(QLabel控制元件顯示)
阿新 • • 發佈:2019-02-16
一、說明:
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(); // 文字個數 #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("關閉閃爍"); } }