日志
长QString 根据所需宽度自动判断换行示例
2017-10-28 13:28
在做打印程序时,先开始用了 宽度 /字体宽度 = 每行个数 的办法,发现对于不同宽度的混合字体的字符串,输出效果一塌糊涂。
于是采用了一个笨办法。对每个字体进行宽度判定,存入到一个临时 linestr ,当linestr的宽度大于设置值时,换行。行个数计算器清零。 QString text = "abckadamlamsdfloi"; text += "MMs1 may optionally also include a foundry name, e.g. (The Qt 2.x syntax, i.e. , is also supported.)"; text += "If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen. If the family isn't available a family will be set using the font matching algorithm."; text += "也是随着时间的积累,对Qt的认识慢慢深刻,这里希望刚会使用Qt的同志们心里问自己几个问题,"; text += "你是否知道Qt和Qt creator的区别?你对qmake的理解?Qt中信号与槽机制是同步还是异步?"; int width = 700; // 纸张宽度或其他宽度 ,为像素值 QFont font = QApplication::font(); QFontMetrics fmt = QFontMetrics(font); int textLength = text.length(); QList<QString> textRows ; QString entity = text; QString linestr ; int entitywidth = fmt.width(entity); // 文本小于纸张宽度,说明只有一行。 if(entitywidth < width){ qDebug() << "textWidth =" <<entitywidth; qDebug()<<"textLength=: " << textLength; textRows.append(entity); qDebug()<< textRows; return; } // 多行时 int count =0; // 每行的字个数,超过设定的宽度时,归零。 int index =0; // 读取字符串的个数,读完所有字符时,存最后一行数据,退出。 for ( ; ; ) { linestr = entity.left(count); if(index ==textLength-1){ qDebug() << "end of the text.index =" << index; textRows.append(linestr); qDebug() << "final row text count =" <<count; break; } int textwidth = fmt.width(linestr); if(textwidth > width) { textRows.append(linestr); entity.remove(0,count); qDebug() << "row text count =" <<count; count = 0; } if(entity.isEmpty()) { qDebug() << "count = " << count <<"index =:"<< index; qDebug() <<" entity is empty"; break; } count ++; index ++; } qDebug()<< textRows; |