#include <cassert>
#include <QDesktopWidget>
#include <QImage>
#include <QPainter>
#include <QPixmap>
#include <QTimer>
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent,Qt::Window), //To allow resizing
ui(new Ui::Dialog),
m_timer(new QTimer)
{
ui->setupUi(this);
//Put the dialog in the screen center
const QRect screen = QApplication::desktop()->screenGeometry();
this->move( screen.center() - this->rect().center() );
//Make a timer tick ever 1000 ms
QObject::connect(m_timer.get(),SIGNAL(timeout()),this,SLOT(onTimer()));
m_timer->start(1000);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void Dialog::paintEvent(QPaintEvent *)
{
//Start the painter
QPainter painter(this);
//Load the background from resources
QPixmap background(":/images/Background11x11.png");
assert(!background.isNull());
//StretchDraw the background on the widget
painter.drawPixmap(
ui->widget->rect(),
background);
//Load the sprite from resources
QPixmap sprite(":/images/Sprite22x22.png");
assert(!sprite.isNull());
//Choose a random x and y coordinate on a white pixel
int x = 0;
int y = 0;
while (1)
{
x = 1 + (std::rand() % 9);
y = 1 + (std::rand() % 9);
//The new position must be on a white pixel
if (background.toImage().pixel(x,y)
== QColor(255,255,255).rgb()) break;
}
//Determine the sprite's position on the painter
const int width = ui->widget->width();
const int height = ui->widget->height();
const double block_width = static_cast<double>(width) / 11.0;
const double block_height = static_cast<double>(height) / 11.0;
//Draw the sprite on the painter
painter.drawPixmap(
static_cast<double>(x) * block_width,
static_cast<double>(y) * block_height,
block_width,
block_height,
sprite);
}
void Dialog::onTimer()
{
this->repaint();
}
|