を使用しQTimer
てラベルのサイズをスムーズに変更しています。マウスをボタンの上に置くとラベルはゆっくりと大きくなり、マウスがボタンから離れるとゆっくりと折りたたまれます (消えるまでサイズが小さくなります)。
フォームのクラスに 2 つのタイマーがあります。
QTimer oTimer, cTimer;//oTimer for expanding, cTimer for collapsing
フォームのコンストラクターで、タイマーの値を設定し、ボタンmouseOver
とmouseOut
シグナルをフォームのスロットに接続しています。
oTimer.setInterval( 25 );
cTimer.setInterval( 25 );
connect( ui.Button,
SIGNAL(mouseEntered(QString)),
this,
SLOT(expandHorizontally(QString)) );
connect( ui.Button,
SIGNAL(mouseLeft(QString)),
this,
SLOT(compactHorizontally(QString)) );
ここで、これらのスロットで、対応するタイマーをスロットに接続し、スロットのサイズを徐々に変更してから、タイマーを開始します。
void cForm::expandHorizontally(const QString & str)
{
ui.Text->setText( str );
connect( &oTimer, SIGNAL(timeout()), this, SLOT(increaseHSize()) );
cTimer.stop();//if the label is collapsing at the moment, stop it
disconnect( &cTimer, SIGNAL(timeout()) );
oTimer.start();//start expanding
}
void cForm::compactHorizontally(const QString &)
{
connect( &cTimer, SIGNAL(timeout()), this, SLOT(decreaseHSize()) );
oTimer.stop();
disconnect( &oTimer, SIGNAL(timeout()) );
cTimer.start();
}
その後、ラベルはサイズの変更を開始します。
void cForm::increaseHSize()
{
if( ui.Text->width() < 120 )
{
//increase the size a bit if it hasn't reached the bound yet
ui.Text->setFixedWidth( ui.Text->width() + 10 );
}
else
{
ui.Text->setFixedWidth( 120 );//Set the desired size
oTimer.stop();//stop the timer
disconnect( &oTimer, SIGNAL(timeout()) );//disconnect the timer's signal
}
}
void cForm::decreaseHSize()
{
if( ui.Text->width() > 0 )
{
ui.Text->setFixedWidth( ui.Text->width() - 10 );
}
else
{
ui.Text->setFixedWidth( 0 );
cTimer.stop();
disconnect( &cTimer, SIGNAL(timeout()) );
}
}
問題: 最初はすべてがスムーズに機能しますが、ラベルがゆっくりと開いたり閉じたりします。ただし、これを数回行うと、そのたびにサイズがどんどん速く変化し始めます (タイマーの間隔がどんどん小さくなっていくように、しかし明らかにそうではありません)。最終的に、数回開いたり閉じたりした後、マウスをボタンの上に置くとすぐにサイズが境界まで大きくなり始め、マウスがボタンから離れるとすぐにサイズがゼロになります。
その理由は何でしょうか?