2012-09-21 65 views
1

基本上我想要做的是爲列表中的每個數字繪製矩形。數字越大,矩形越大。 我的問題是,當我真的想要這樣做時,一步一步地在每張圖畫之間等待幾秒鐘。我已經尋找了一些解決方案,但我無法讓他們爲這個特殊情況工作。我看到我可以使用fflush釋放緩衝區中的任何內容,但我不知道如何使用它。在qt中使用paintevent的循環內睡眠C++

QPainter painter(this); 
painter.setRenderHint(QPainter::Antialiasing, true); 
painter.setBrush(QBrush(Qt::green, Qt::SolidPattern)); 
int weight=300/lista.size; 
int posx=weight; 
for (int i=1; i<=lista.size; i++){ 
     List_node * node = list.get_element_at(i); 
      int num=node->getValue(); //this returns the value of the node 
     if (i==3){ 
       painter.setBrush(QBrush(Qt::red, Qt::SolidPattern)); // this line is to draw a rectangle with a different color. Testing purposes. 
     } 
     painter.drawRect(posx,400-(num*10),weight,num*10); 
     sleep(1); //this sleep isn't working correctly. 
     painter.setBrush(QBrush(Qt::green, Qt::SolidPattern)); 
     posx+=weight; 
} 

任何幫助將非常感激。

回答

2

sleep()不會爲此工作 - 它會阻止Qt事件循環,並保持Qt在睡眠時不做它的工作。

你需要做的是讓一個或多個成員變量記住要繪製的圖像的當前狀態,並實現paintEvent()以僅繪製當前單個圖像。 paintEvent()(就像在Qt的GUI線程中運行的每個函數一樣)應該總是立即返回,並且永遠不會睡眠或阻塞。然後,爲了實現事物的動畫部分,設置一個QTimer對象來定期爲你調用一個槽(例如每1000mS一次,或者你經常喜歡)。實現該插槽以將動態序列中的成員變量調整爲其下一個狀態(例如,rectangle_size ++或其他),然後在您的小部件上調用update()。 update()會告訴Qt儘快在你的小部件上再次調用paintEvent(),所以你的顯示將在你的slot方法返回後很快更新到下一幀。

下面是該技術的一個簡單例子;運行時顯示紅色矩形越來越小:

// begin demo.h 
#include <QWidget> 
#include <QTimer> 

class DemoObj : public QWidget 
{ 
Q_OBJECT 

public: 
    DemoObj(); 

    virtual void paintEvent(QPaintEvent * e); 

public slots: 
    void AdvanceState(); 

private: 
    QTimer _timer; 
    int _rectSize; 
    int _growthDirection; 
}; 

// begin demo.cpp 
#include <QApplication> 
#include <QPainter> 
#include "demo.h" 

DemoObj :: DemoObj() : _rectSize(10), _growthDirection(1) 
{ 
    connect(&_timer, SIGNAL(timeout()), this, SLOT(AdvanceState())); 
    _timer.start(100); // 100 milliseconds delay per frame. You might want to put 2000 here instead 
} 

void DemoObj :: paintEvent(QPaintEvent * e) 
{ 
    QPainter p(this); 
    p.fillRect(rect(), Qt::white); 
    QRect r((width()/2)-_rectSize, (height()/2)-_rectSize, (_rectSize*2), (_rectSize*2)); 
    p.fillRect(r, Qt::red); 
} 

void DemoObj :: AdvanceState() 
{ 
    _rectSize += _growthDirection; 
    if (_rectSize > 50) _growthDirection = -1; 
    if (_rectSize < 10) _growthDirection = 1; 
    update(); 
} 

int main(int argc, char ** argv) 
{ 
    QApplication app(argc, argv); 

    DemoObj obj; 
    obj.resize(150, 150); 
    obj.show(); 
    return app.exec(); 
} 
+0

非常感謝!這解決了它。 –