工作需要调用Qpainter的drawtext函数,发现很不只能,对于QString不能自动断行,QString中加入"\n"也不行,现在考虑只能把QString多次截断,然后多次调用drawtext,比如一段字符串有中英文,长度很长,在scrollview里显示也很长,需要换行显示全部,不考虑用滚动条,实在太长了,请教有什么办法可以按固定长度进行截断重组?
class FontMetricsEx : public QFontMetrics
{public:
FontMetricsEx ( const QFont & font ):QFontMetrics(font)
{
}
FontMetricsEx ( const QFont & font, QPaintDevice * paintdevice )
:QFontMetrics(font,paintdevice)
{
}
FontMetricsEx ( const QFontMetrics & fm ):QFontMetrics(fm)
{
}
QString elidedTextEx ( const QString & text, Qt::TextElideMode mode, int width, int flags = 0 ) const
{
if (mode == Qt::ElideNone) {
QString strRet = QFontMetrics::elidedText(text,Qt::ElideRight,width,flags);
QChar ellipsisChar(0x2026);
QString dotDotDot(QLatin1String("..."));
QString elidedString = ellipsisChar;
if(strRet.length() < text.length()){
if(strRet.lastIndexOf(ellipsisChar) == -1){
elidedString = dotDotDot;
}
strRet = strRet.left(strRet.length() -elidedString.length());
}
return strRet;
}
else{
return QFontMetrics::elidedText(text,mode,width,flags);
}
}
};
///
QFont font=_textEdit->font();
FontMetricsEx * Fmt =new FontMetricsEx (font);
QString strText = _textEdit->text();
int max_text_width = 64;
QStringList list;
while(strText != ""){
QString text_line = Fmt->elidedTextEx(strText,Qt::ElideNone,max_text_width);
list << text_line;
strText = strText.right(strText.length() - text_line.length());
}
参考:http://bbs.csdn.net/topics/390497684