我有一些数据会不断变化。我通过 QPainter 将这些数据绘制成一行,并希望通过 QTimer 进行动态更新(每秒更新一次),但数据只会在我关闭绘画窗口时更新,它不会在窗口中实时更新。我哪里错了??这是代码:
#include <QtGui/QApplication>
#include <QApplication>
#include <QLabel>
#include <QWidget>
#include <QPainter>
#include <QTimer>
#define WINDOW_H 512
#define WINDOW_W 512
unsigned char *pMergedData;
class DrawDemo : public QWidget {
Q_OBJECT
public:
DrawDemo( QWidget *parent=0);
public slots:
void MyUpdate();
protected:
void paintEvent(QPaintEvent*);
private:
QTimer *timer;
};
void DrawDemo::MyUpdate(){
test_plot();
update();
}
DrawDemo::DrawDemo( QWidget *parent) :QWidget(parent){
pMergedData = (unsigned char *)malloc(200*sizeof(short));
QTimer *timer = new QTimer(this);
connect( timer, SIGNAL( timeout() ), this, SLOT( MyUpdate() ) );
timer->start( 1000 ); //ms
}
void DrawDemo::paintEvent( QPaintEvent * ) {
short *buf16 = (short *)pMergedData;
QPainter painter( this );
QPoint beginPoint;
QPoint endPoint;
painter.setPen(QPen(Qt::red, 1));
for( int i=0; i<199; i++ ) {
beginPoint.setX( 2*i );
beginPoint.setY( WINDOW_H - buf16[i] );
endPoint.setX( 2*i+1 );
endPoint.setY( WINDOW_H - buf16[i+1]);
painter.drawLine( beginPoint, endPoint );
}
}
int test_plot(){
counter_globol ++;
if(counter_globol%2==0){
for(int i=0; i<200; i++ ) {
pMergedData[i] = 100;
}
}else{
for(int i=0; i<200; i++ ) {
pMergedData[i] = i;
}
}
return 0;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DrawDemo *drawdemo = new DrawDemo( 0 );
drawdemo->setWindowTitle("QPainter");
drawdemo->resize(WINDOW_W, WINDOW_H);
drawdemo->show();
a.exec();
free(pMergedData);
return 0;
}