2012-09-21 1 views
1

기본적으로 내 목록에서 각 숫자에 대해 사각형을 그립니다. 숫자가 클수록 사각형이 커집니다. 제 문제는 제가 실제로 그것을하고, 단계별로하고, 모든 그림 사이에 몇 초를 기다리고 싶을 때입니다. 나는 몇 가지 해결책을 찾았지만이 특별한 경우를 위해 일할 수는 없습니다. 버퍼에있는 내용을 릴리즈하기 위해 fflush를 사용할 수 있다는 것을 알았지 만, 어떻게 이것을 사용할 수 있을지 모르겠습니다.Qt C++에서 paintevent를 사용하는 루프 내부에서 잠을 자다

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()는 가능하면 빨리 위젯에서 paintEvent()를 다시 호출하도록 Qt에 지시하므로 슬롯 메소드가 반환 된 직후에 디스플레이가 다음 프레임으로 업데이트됩니다.

다음은이 기술의 간단한 예입니다. 실행하면 크고 작아지는 빨간색 사각형이 표시됩니다.

// 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

감사합니다. 그것으로 해결되었습니다. –