Qt实现长文件名(字符串)在QLabel中自适应缩短
一、应用场景简述
当在有限宽度的QLable中显示很长的文件名/字符串时,超出QLabel宽度部分将不会显示,此时采取缩短文件名策略(也可实现为字符串滚动动画)可以缓解这一问题。在实现这一想法的过程中,先后提出两个解决方案。遂再次分享给大家。
二、方案实现
//方案1:简单的保留前面几个字符,去出中间的几个字符,保留后面几个字符
- QString scalText(QString org)
- {
- QString result;
- const quint16 strLen = org.length();
- int index = org.lastIndexOf(".");
- if(-1 == index){ //如果返回-1表示没找到
- //无后缀名
- QString fileName = org;
- if( strLen < 11)
- result = fileName;
- else{
- result = fileName.mid(0,3); //取前三个字符
- result += "...";
- result = fileName.mid(strLen-6,6); //取后6个字符
- }
- }
- else{
- //有后缀名
- if( strLen < 11){
- result = org;
- }
- else{
- const QString fileName = org.left(index); //文件名
- const quint16 fileNameLen = fileName.length();
- const QString fileExtName = org.right(strLen - 1 - org.lastIndexOf(".")); //文件扩展名
- result = fileName.mid(0,3);
- result += "..." + fileName.mid(fileNameLen-3,3); //取后3个字符
- result += "." + fileExtName; //追加后缀名
- }
- }
- return result;
- }
此实现方案灵活性差,通用性差,而且在文件名/字符串中混合这ASCII码和宽字符时显示效果极差。
//方案2:根据QLabel的实际宽度、字体的尺寸属性等对文件名进行缩短
//目标: 将“长文件名测试文件-长文件名测试文件-长文件名测试文件.wmv 1203MB”缩短为“长文件名...测试文件.wmv 1203MB”
//定义: QString scalText(QString org, unsigned int showWidth ,QString arg1="");
//参数:org-待缩短的字符串/文件名,如上面的“长文件名测试文件-长文件名测试文件-长文件名测试文件.wmv”
// showWidht-QLabel的实际宽度
// arg1-追加到org后面的补充字符串
- QString scalText(QString org, unsigned int showWidth ,QString arg1)
- {
- QString result;
- QString chngeStr("...");
- QFontMetrics fm(QFont("微软雅黑",10));
- const unsigned int labWidthPxs = showWidth-10; //label的固定宽度
- int textWidthInPxs = fm.width(org);
- int unitsWidthPxs = fm.width(arg1);
- int blankWidthPxs = fm.width(" ");
- int chngeWidthPxs = fm.width(chngeStr);
- unsigned int remainWidthPxs = labWidthPxs - unitsWidthPxs - blankWidthPxs - chngeWidthPxs;
- if(textWidthInPxs < remainWidthPxs){
- result = org;
- }
- else{
- short preIndex = 4, rearIndex =4; //保留前4个字符
- int pickUpWidthPxs = 0;
- do{
- ++rearIndex;
- QString pickUp = org.mid(preIndex,rearIndex-preIndex);
- pickUpWidthPxs = fm.width(pickUp);
- QString preFix = org.mid(0,preIndex);
- QString sufFix = org.mid(rearIndex, org.length()-rearIndex);
- result = preFix + chngeStr + sufFix;
- }while(textWidthInPxs-pickUpWidthPxs > remainWidthPxs);
- }
- return result;
- }
测试:
ui->label.setText(scalText(fileName, ui->label.Width(), "1023MB");
三、更新
第一次更新 2016-09-05
http://blog.csdn.net/qq2399431200/article/details/52438562