应用场景:
在使用QLabel固定宽度以及固定高度时,需要根据字符串行数来设置控件的对齐方式(即:setAlignment)。自动换行时同时有中文或者英文或者其他文字,所以计算高度或行数的方法也需要根据自动换行来获得。QListViewItem QTableViewItem 类似自动换行也可参考。
如:我在固定宽高的QLabel中要显示字符串:QString qsStr = "Qt Creator provides a cross-platform, complete integrated development environment (IDE) for application developers to create applications for multiple desktop, embedded, and mobile device platforms, such as Android and iOS. It is available for Linux, macOS and Windows operating systems. For more information, see Supported Platforms.";
如果不设置对齐方式,显示则不友好。
如果不计算,直接设置顶部对齐,单行字符串显示也会不好看。
QFontMetrics fm = ui->label->fontMetrics();
int iLineHeight = fm.height();
QRect newRect = fm.boundingRect(QRect(0, 0, 310, iLineHeight), Qt::TextWordWrap, qsText);
int iLineCount = newRect.height() / iLineHeight;
if(iLineCount > 1){
ui->label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
}else{
ui->label->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
}
根据行数设置对齐方式后显示友好很多