12,951
回編集
(→概要) |
(→概要) |
||
1行目: | 1行目: | ||
== 概要 == | == 概要 == | ||
Qtにおいて、<code>QLabel</code>クラスを使用してラベルをコントロールする手順を記載する。<br> | |||
<br><br> | |||
== テキストの折り返し == | |||
ラベルの横幅に合わせて文字列を分割して、改行コードを入れた文字列を返す。<br> | |||
<code>QLabel</code>クラスの<code>wordWrap</code>メソッドも存在する。<br> | |||
<br> | |||
これは、ラベルの横幅が固定されている場合、長い文字列を表示する時に使用する。<br> | |||
もし、文字列がラベルの横幅に収まる場合、分割・改行せずに文字列を返す。<br> | |||
<br> | |||
<u>※注意</u><br> | |||
<u>フォントの設定を行っていない場合、サイズを正しく計算できないことがある。</u><br> | |||
<syntaxhighlight lang="c++"> | |||
QString MainWindow::wrapLabelText(QLabel *label, QString text) | |||
{ | |||
int mxWidth = label->width(); | |||
QFontMetrics fm(label->fontMetrics()); | |||
if(fm.width(text) <= mxWidth) | |||
{ | |||
return text; | |||
} | |||
QString tmpStr = ""; | |||
QString lineStr = ""; | |||
for(int i = 0; i < text.length(); i++) | |||
{ | |||
QString str = text.mid(i, 1); | |||
if(str == "\n") | |||
{ | |||
tmpStr += lineStr + "\n"; | |||
lineStr = ""; | |||
continue; | |||
} | |||
if((fm.width(lineStr) + fm.width(str)) >= mxWidth) | |||
{ | |||
tmpStr += lineStr + "\n"; | |||
lineStr = ""; | |||
} | |||
lineStr += str; | |||
} | |||
tmpStr += lineStr; | |||
return tmpStr; | |||
} | |||
</syntaxhighlight> | |||
<br><br> | <br><br> | ||