QT 实现在ui控件QLabel中实现滚动字幕

题记:前一段时间作为小白的我,搞了一下QT,在如何实现在ui一个子控件中进行字幕滚动/图片显示卡住了,经过资料及百度查询,终于做出来了。由于之前没人有详细的教程,所以我记录了一下,把这个分享这里,希望对大家帮助。

QPainter 在ui子控件中实现滚动文字显示

在使用QT中的QPainter实现滚动图片时,发现其职能在当前类中实现而不能对其指定对象。因此,本文介绍如何实现在UI子控件中实现QPainter,实现滚动字幕显示。

       第一步:创建带ui的widgets工程。

      

以下是创建完成之后的工程:

 


       第二步:打开hello.ui拉一个QLabel控件到窗口上面


在这里我去掉了文字,以及改变了空间背景颜色。


第三步:在工程的Header目录下添加头文件

 

 

创建好后如下图所示,并加上圈内代码到myqlabel.h:

 

第四步:在source目录下添加myqlabel.cpp文件



然后添加下面代码:

#include<QPainter>

#include"myqlabel.h"

#include<QDebug>

#include<QtWidgets/qframe.h>

#include<QWidget>

#include<QTimer>

#include<sys/time.h>

mypaint::mypaint(QWidget*parent) :QLabel(parent)

{

    curIndex =0;

    showText ="hello I am here";

    charWidth=fontMetrics().width("a");

    QTimer *timer =new QTimer(this);

   connect(timer,SIGNAL(timeout()),this,SLOT(updateIndex()));

    timer->start(300);

}

void mypaint::paintEvent(QPaintEvent*event)

{

    QPen pen;

    QPainter painter(this);

    pen.setColor(QColor(255,0,255));

    pen.setStyle(Qt::DashDotDotLine);

    QFont font("楷体",20,QFont::Bold);

    painter.setPen(pen);

    painter.setFont(font);

   painter.drawText(0,50,showText.mid(curIndex));

   painter.drawText(width()-charWidth*curIndex,50,showText.left(curIndex));

}

voidmypaint::updateIndex()

{

    update();

    curIndex++;

    if(curIndex*charWidth>width())

        curIndex =0;

}

 

第五步:进行控件类的提升操作,使其脱离ui 窗口类的包含。

1、打开ui文件,如下图

 

 

2、选择鼠标右键

 

2、右键点击后,选中:Promote to …..

3、如下:选择QLabel ,输入我们要提升的类名:mypaint  ,然后点击添加:Add


4、按下图操作

 

5、至此完成所有操作。

第六步:保存->编译->运行,结果如下:


猜你喜欢

转载自blog.csdn.net/Chasing_Chasing/article/details/77431758