我創建了一個矩形,並希望它與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();
}
您的粘貼代碼沒有正確縮進,使其難以閱讀。請通過編輯問題來正確縮進代碼。 –