当前位置:网站首页>Qlabel text scrolling horizontally

Qlabel text scrolling horizontally

2022-06-25 23:35:00 The struggle history of polar bear

First on the renderings :

Look at the source code :

1. Adaptive function , Judge label Whether the text needs to scroll .

void MLabel::upateLabelRollingState()
{
    //   Get text size , Less than the length of the text box , No scrolling required 
    QFont ft = font();
    ft.setPointSize(fontSize);

    QFontMetrics fm(ft);
    int nW = fm.width(text());

    left = 0;
    //   Turn on text box scrolling 
    if(nW > width())
    {
        timerId = startTimer(100);
    }
    //   Turn off text box scrolling 
    else
    {
        if(timerId >= 0)
        {
            killTimer(timerId);
            timerId = -1;
        }
    }
}

 2. Move the text position regularly

void MLabel::timerEvent(QTimerEvent *e)
{
    if(e->timerId() == timerId && isVisible())
    {
        //   Every time I move left 1 Pixel 
        left += 1;

        //   Determine whether the cycle has been completed , When finished, restore the starting position , Start the cycle again 
        QFont ft = font();
        ft.setPointSize(fontSize);
        QFontMetrics fm(ft);
        int txtWidth = fm.width(text());
        int spaceWidth = fm.width(strSpace);

        if((txtWidth + spaceWidth) < left)
            left = 0;

        repaint();
    }

    QLabel::timerEvent(e);
}

3. Redraw events , Dynamically display text

void MLabel::paintEvent(QPaintEvent *e)
{
    QPainter p(this);

    //   Get the size of the text box 
    QRect rc = rect();
    rc.setHeight(rc.height() - 2);
    rc.setWidth(rc.width() - 2);

    //   Set the font of the text to be drawn 
    QFont ft = font();
    ft.setPointSize(fontSize);
    p.setFont(ft);
    p.setPen(QPen(Qt::red));

    //   Set the starting position of the drawn text , That is, how much to move the text to the left 
    rc.setLeft(rc.left() - left);

    //   If the text has been displayed to the end , Then add the text again , Make a circular scrolling effect 
    QString strText = text();
    if(timerId >= 0)
        strText += strSpace + text();

    //   Draw text 
    p.drawText(rc, Qt::AlignVCenter, strText);
}

4. Use effect , Setting text in 、 The scaling event calls the adaptive function twice .

void MLabel::setText(const QString & txt)
{
    QLabel::setText(txt);

    upateLabelRollingState();
}

void MLabel::resizeEvent(QResizeEvent *e)
{
    QLabel::resizeEvent(e);

    upateLabelRollingState();
}

complete , When using , take QLabel Upgrade to MLabel that will do .

Finally, the source download address is attached :https://download.csdn.net/download/chenxipu123/10966082

Make complaints about it :CSDN Do not set the download points required for resources , So the source code cannot be shared for free .

原网站

版权声明
本文为[The struggle history of polar bear]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206252013020191.html