2016-03-18 29 views
0

我創建了一個矩形,並希望它與QTimer一起移動,我想知道QTimer的方法是如何正確工作的。這段代碼正在運行,但我繪製的圖不會移動。 .H 頭文件 的#ifndef WIDGET_Hqtimer的基本工作是什麼?

#define WIDGET_H 

#include <QWidget> 

namespace Ui { 
class Widget; 
} 

class Widget : public QWidget 
{ 
Q_OBJECT 

public: 
    explicit Widget(QWidget *parent = 0); 
void paintEvent(QPaintEvent *event); 
~Widget(); 
private slots: 
void update(); 
private: 
Ui::Widget *ui; 
}; 

這是.cpp文件

的.cpp

#include "widget.h" 
#include "ui_widget.h" 
#include<QPainter> 
#include<QTimer> 



Widget::Widget(QWidget *parent) : 
QWidget(parent), 
ui(new Ui::Widget) 
{ 
ui->setupUi(this); 
QTimer *timer = new QTimer(this); 
timer->setInterval(1000); 
connect(timer, SIGNAL(timeout()), this, SLOT(update())); 
timer->start(); 

} 

Widget::~Widget() 
{ 
delete ui; 
} 
void Widget::paintEvent(QPaintEvent *event) 
{ 

QPainter painter(this); 

    painter.drawRect(50,80,70,80); 

} 

void Widget::update() 

{ 
update(); 
} 
+0

您的粘貼代碼沒有正確縮進,使其難以閱讀。請通過編輯問題來正確縮進代碼。 –

回答

1

你說 「我畫了圖中是不動的。」在你的代碼中,我看不到移動圖形的代碼,我只看到一個正在繪製的靜態矩形。另外,update()函數調用自己,導致無限遞歸。從您的代碼中刪除update(),基類實現QWidget::update()做了正確的事情(安排呼叫paintEvent()),無需重新實現update()

1

首先,update() slot方法已經有了特定的含義和用途,您不應該爲了其他目的而重寫它。此外,它不是virtual,它告訴你,即使意味着被覆蓋(並且這樣做會導致非常混亂的情況)。所以重命名你自己的方法... updateAnimation()什麼的。

然後你需要添加私有成員變量爲您的矩形位置,說rectXrectYrectWidthrectHeight(或只是單一QRect如果您願意)。一些代碼片段可以幫助您理解:

void Widget::paintEvent(QPaintEvent *event) 
{ 
    // default setting is that Qt clears the widget before painting, 
    // so we don't need to worry about erasing previous rectangle, 
    // just paint the new one 
    QPainter painter(this); 
    painter.drawRect(rectX, rectY, rectWidth, rectHeight); 
} 


void Widget::updateAnimation() 
{ 
    // modify rectX, rectY, rectWidth and rectHeight here 
    update(); // make Qt do redrawing 
} 
相關問題