Qt如何在循环中更新GUI

Qt如何在循环中更新GUI,qt,Qt,我需要更新屏幕以显示按钮是如何移动的。 这是我的密码: void mouseReleaseEvent(QMouseEvent *event){ double b=(button->x()*event->y())/(button->x()-1); double k=(button->y()-b)/button->x(); int time=0; fnl=false; if(event->button()==Qt::Left

我需要更新屏幕以显示按钮是如何移动的。 这是我的密码:

void mouseReleaseEvent(QMouseEvent *event){
    double b=(button->x()*event->y())/(button->x()-1);
    double k=(button->y()-b)/button->x();
    int time=0;
    fnl=false;
    if(event->button()==Qt::LeftButton)
    {
        while(!fnl)
        {
            int mX=button->x()-1;
            int mY=k*(button->x()-1)+b;
            button->setText(QString::number(b));
            button->move(mX,mY);
            QThread::sleep(1);
            //here I need to update screen and show button
        }

    }
}

但它不会更新GUI。它只是在循环中播放。

定时器是最好的选择。如果你想使用暴力,你可以打电话

qApp->processEvents();

在你的循环中。丑陋但却能完成任务

切勿在GUI线程中使用
QThread::sleep()
,否则会阻止GUI线程执行任何操作。相反,您可以使用
QTimer
来计划在稍后的时间点运行的内容。此外,插槽/函数应尽可能短并优化,以便将控制权返回到事件循环并能够处理

您可能需要查看类似的问题。 这里可以应用相同的技术来解决这个问题,方法是将while循环替换为插槽和间隔设置为
0
QTimer
但是Qt可以使用完成所有工作,下面是一个按钮在单击时移动的示例:

#include <QtWidgets>

int main(int argc, char* argv[]){
    QApplication a(argc, argv);
    //create and show button
    QPushButton button("Animated Button");
    button.move(QPoint(100, 100));
    button.show();
    //create property animator object that works on the position of the button
    QPropertyAnimation animation(&button, "pos");
    //set duration for the animation process to 500ms
    animation.setDuration(500);

    //when the button is clicked. . .
    QObject::connect(&button, &QPushButton::clicked, [&]{
        //set the starting point of the animation to the current position
        animation.setStartValue(button.pos());
        //set the ending point to (250, 250)
        animation.setEndValue(QPoint(250, 250));
        //start animation
        animation.start();
    });

    return a.exec();
}
#包括
int main(int argc,char*argv[]){
质量保证申请a(argc、argv);
//创建和显示按钮
QPushButton按钮(“动画按钮”);
按钮。移动(QPoint(100100));
按钮。显示();
//创建在按钮位置上工作的特性animator对象
QPropertyAnimation动画(&按钮,“位置”);
//将动画过程的持续时间设置为500毫秒
动画。设置持续时间(500);
//单击按钮时。
QObject::connect(&button,&QPushButton::单击,[&]{
//将动画的起点设置为当前位置
animation.setStartValue(button.pos());
//将终点设置为(250250)
setEndValue(QPoint(250250));
//启动动画
animation.start();
});
返回a.exec();
}

Qt还提供了使用动画框架

你认识克蒂默吗?我建议您创建一个由计时器定期调用的函数。在函数中,您可以检查按钮是否按下,如果是,则更新其位置。是否有类似于
timer1的事件处理程序。在C#timer中勾选
?谢谢。正是我一直在寻找的东西!当使用
processEvents()
时,您的代码应该是,这意味着您应该准备好再次传递使您进入此插槽的相同事件。在这种情况下,插槽本身会再次被调用(在某些情况下,这种情况可能会无限期地发生)。很可能这不是你想要的行为。看看@Mike,同意。我应该说“难看但经常能完成任务”……关键是要把工作做好。当您养成了编写异步代码的习惯时,它会打开许多其他的可能性,并使生活变得更加轻松。下一步是养成这种习惯。