#include "window.h"
#include <QPainter>
#include <QTimer>
#include <QMouseEvent>

Window::Window(QWidget *parent) :
	QWidget(parent), squareSize(20), x(10), y(30), dx(1), dy(-1)
{
	setAutoFillBackground(false);
	QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), SLOT(update()));
	timer->start(10);
}

void Window::mousePressEvent(QMouseEvent *event)
{
	if (event->button() == Qt::LeftButton)
	{
		x = event->pos().x() - squareSize/2;
		y = event->pos().y() - squareSize/2;
	}
}

void Window::paintEvent(QPaintEvent*)
{
	QSize s = size();
	x += dx;
	y += dy;
	if (s.width() <= squareSize)
		x = 0;
	else if (x < 0)
		x = -x, dx = abs(dx);
	else if (x + squareSize > s.width())
		x = s.width()*2 - squareSize*2 - x, dx = -abs(dx);
	if (s.height() <= squareSize)
		y = 0;
	else if (y < 0)
		y = -y, dy = abs(dy);
	else if (y + squareSize > s.height())
		y = s.height()*2 - squareSize*2 - y, dy = -abs(dy);

	QPainter painter(this);
	painter.fillRect(QRect(x, y, squareSize, squareSize), Qt::black);
}
