gpt4 book ai didi

c++ - 每次启动/停止时 QTimer 变得更快

转载 作者:搜寻专家 更新时间:2023-10-31 01:13:25 27 4
gpt4 key购买 nike

我正在使用 QTimer 平滑地更改标签的大小:当我将鼠标悬停在按钮上时它应该缓慢增长,当我将鼠标悬停在按钮上时它应该缓慢折叠(减小它的大小直到它消失)鼠标离开按钮。

我的表单类中有两个计时器:

QTimer oTimer, cTimer;//oTimer for expanding, cTimer for collapsing

在我的表单构造函数中,我正在设置计时器的值并将按钮的 mouseOvermouseOut 信号连接到我的表单槽:

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()) );
}
}

问题:起初一切顺利,标签慢慢打开和关闭。但是,如果它这样做了几次,它就会开始越来越快地改变大小(就好像计时器的间隔越来越小,但显然不是)。最终,在几次打开/关闭之后,当我将鼠标悬停在按钮上时,它开始立即将其大小增加到边界,然后立即折叠到零大小当鼠标离开按钮时。

这可能是什么原因?

最佳答案

我会建议事件正在等待处理,排队事件的数量会随着时间的推移而增加。可能是因为两个计时器事件之间的事件未完全处理或由于程序的其他部分。

为什么不只使用一个计时器?您可以走得更远,只使用插槽来处理尺寸变化事件。其他插槽只是用于更改什么类型的更改:

void cForm::connectStuff(){
connect( &oTimer, SIGNAL(timeout()), this, SLOT(changeSize()) );
connect(
ui.Button,
SIGNAL(mouseEntered(QString)),
this,
SLOT(expandHorizontally())
);
connect(
ui.Button,
SIGNAL(mouseLeft(QString)),
this,
SLOT(compactHorizontally())
);
}

void cForm::expandHorizontally(){
shouldExpand = true;
}

void cForm::compactHorizontally(){
shouldExpand = false;
}

void cForm::changeSize(){
if(shouldExpand)
increaseHSize();//call the function which expand
else
decreaseHSize();//call the function which compact
}

关于c++ - 每次启动/停止时 QTimer 变得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12528184/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com