【问题标题】:Refreshing MainWindow in a loop to simulate a move of QWidget in QT循环刷新MainWindow以模拟QT中QWidget的移动
【发布时间】:2015-03-19 08:21:31
【问题描述】:

我是 QT 的新手,我的问题是循环刷新页面以在 QWidget 上移动。
详细地说,我有太多的点(这是一个椭圆跟随的路径,它们将被绘制为直线),我有一个椭圆将根据给定的两个点在屏幕上移动。在其移动过程中,路径发生了变化。因此将根据新路径再次绘制线条,椭圆应遵循新路径。我做了如下:

void MainWindow::paint(...){
painter.drawEllipse(circle) //circle is QRectF
//Also I need to draw lines according to pathPlanned
}



bool MainWindow::replan(){
//it calculates the planned path and if the ellipse does not reached the destination it can change the planned path here 
}

void MainWindow::execute(){
   while(replan()){
      for (it = plannedPath->begin(); it != plannedPath->end(); it++){
          //Lines should be redraw according to new pathPlanned
       }
    circle(...) // new position of ellipse is changed here
    // I tried to put QThread::msleep(10) but I learned that it blocks GUI and then deleted it.
     }
}

我的问题是循环运行得如此之快(像往常一样)并且在完成所有操作之前它无法刷新页面。然后立即在目的地上绘制椭圆。我看不到椭圆的移动。 我该如何解决?

【问题讨论】:

    标签: qt qwidget qpainter


    【解决方案1】:

    不要使用 QThread::msleep(10),而是使用以下

    QEventLoop loop;
    QTimer::singleShot(100, &loop, SLOT(quit()));
    loop.exec();
    

    这将在每次重绘椭圆后处理事件,以便更新 UI

    【讨论】:

      【解决方案2】:

      您需要为此使用Qt animation framework。官方文档中有很多示例。在这种情况下,您不会阻塞主事件循环,并且您的动画会很流畅。

      如果您使用自定义绘图,请不要忘记调用QWidget::repaint()QWidget::update() 来刷新小部件内容。

      不要在主线程中使用长时间循环。使用计时器 + 插槽。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-24
        • 2015-03-30
        • 1970-01-01
        • 2013-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多