本文介绍了QLabel 自动换行模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签,有时会包含没有空格的长文本(计算机中的路径).

I have a label that sometimes contain a long text with no spaces (path in the computer).

所以自动换行非常奇怪.

So word-wrap wraps it very weirdly.

有没有办法让标签的自动换行在单词中间或不只在空格处中断?

Is there a way to make the word-wrap of the label break in the middle of the word or not only at white spaces?

推荐答案

这并不优雅,但确实有效...
所以说头类有 Private:

This isn't elegant but does work...
So say header class has Private:

QLabel *thisLabel;
QString *pathName;
QString *pathNameClean;

当然还有在某处定义 thisLabel .所以如果它这么简单就好了......

and of course defining thisLabel some where. so it would be nice if it was this simple....

thisLabel->setWordWrap(true);

当且仅当单词有断点时才可以(应该避免哪些路径)

that's fine IF AND ONLY IF the word has break points(WHICH PATHS SHOULD AVOID)

因此,如果稍后出于 QFile 目的需要它,请将实际路径保留在单独的字符串中.然后手动定义每行号一个字符,并在字符串中插入空格....所以我们会说 50 个字符是一个很好的宽度...

SO keep your actual path in a separate string if you need it for QFile purposes later.Then manually define a character per line number, and insert the spaces into the string....so we'll say 50 chars is a good width...

    pathNameClean = new QString(pathName);

    int c = pathName->length();

    if( c > 50)
    {
        for(int i = 1; i <= c/50; i++)
        {
            int n = i * 50;
            pathName->insert(n, " ");
        }
    }
    thisLabel->setText(pathName);

Shazam.... 模拟 WordWrap,没有原始空格...

Shazam.... simulated WordWrap with no original spaces...

请记住,pathName 字符串现在仅用于漂亮的 QLabel 目的,而 pathNameClean 字符串是实际路径.如果您尝试打开带有空格注入路径的文件,Qt 程序将崩溃.....

just remember that pathName string is now just for pretty QLabel purposes and that the pathNameClean string is the actual path. Qt programs will crash if you try to open a file with a space injected path.....

(如果没有简单的类方法,很可能只需要几行代码即可...以及为什么解决问题是程序员最好的工具!)

(if there's no simple class method it's likely just a few lines of code to do... and why problem solving is a programmers best tool!)

这篇关于QLabel 自动换行模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:05